[React]07. 리액트 스타일 적용하기

4578 단어 React리액트React

리액트 컴포넌트에 스타일링을 하는 방법에는 여러가지가 있는데요! 오늘은 styled-components를 사용하는 방법에 대해서 정리해보려고 합니다.

📗 styled-components

styled-components는 자바스크립트 파일에서 css를 사용할 수 있게 해주는 대표적인 CSS-in-JS 라이브러리입니다.

CSS-in-JS

📕 styled-components 사용해보기!

먼저, 아래 명령어를 사용하여 프로젝트에 라이브러리를 설치하여 줍니다.

npm install --save styled-components

그리고 스타일링 할 코드를 작성해주세요! 저는 Main 컴포넌트를 만들고 <App />에 추가해두었습니다.

import React from "react";
const Main = () => {
  return (
    <div>
      <h1>Main</h1>
      <button>click me!</button>
    </div>
  );
};
export default Main;

이제 위에 코드에 스타일을 적용해보도록 할게요!

저는 style.js라는 이름으로 파일을 하나 생성하였어요! 생성한 파일 상단에 styled-components에서 styled을 임포트합니다.

import styled from "styled-components";

그리고 원하는 스타일을 적용해보세요!

import styled from "styled-components";

export const Container = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 300px;
  border: 1px solid #c4c4c4;
  margin: 50px;
  padding: 40px;
  box-shadow: rgb(0 0 0 / 20%) 0px 1rem 2rem;
`;

export const ColorButton = styled.button`
  width: 200px;
  height: 60px;
  font-weight: bold;
  border-radius: 5px;
  border: 2px solid #ff6c6c;
  background: #f7cac9;
  color: #ffffff;
  cursor: pointer;

  &:hover {
    background: #ffb4b4;
  }
`;

export const Title = styled.h1`
  color: #8ca4cf;
`;

좋은 웹페이지 즐겨찾기