React - Styled Components 정리

이재호·2024년 12월 3일

React

목록 보기
11/14

오늘은 styled-components에 대해서 정리를 하려고 한다.
평소에 프로젝트를 진행할 때에는 기본적인 내용만 사용하면 되기에 가볍게 사용했는데, 최근 회사에서 styled-components를 적용할 때 코드를 깔끔하게 하기 위해 고민하면서 공부한 내용을 정리해 보도록 하자!!


1. 기존 컴포넌트에 styled-components를 확장하여 사용하자

평소에 차트 혹은 테이블 등 다양한 라이브러리에서 선언된 컴포넌트를 디자인하기 위해서는 class 혹은 tailwind 등을 사용하여 css를 적용했었지만, styled-components를 확장하여 사용할 수 있다.
또는 기존에 만든 styled-components에 새로운 기능을 넣고 싶은 경우에도 확장하여 사용할 수 있다.

예시

import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import styled from "styled-components";

const TableTest = ({ data }) => {
  return (
    <TableContainer>
      <Table>
        <TableHead>
          <TableRow>
            {columns.map((column) => (
              <TableCell key={column}>
                {column === "category" ? "분류" : column}
              </TableCell>
            ))}
          </TableRow>
        </TableHead>
        <TableBody>
          {data.map((row, rowIndex) => (
            <TableRow key={rowIndex}>
              {columns.map((column) => (
                <TableCell key={`${rowIndex}-${column}`}>
                  {row[column]}
                </TableCell>
              ))}
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
};

이러한 상황에서 TableHead에 background-color 속성을 넣어줘서 바탕화면의 색을 변경하고 싶은 경우

const StyledTableHead = styled(TableHead)`
    background-color: blue;
`;

이와 같이 기존 컴포넌트를 확장하여 css 옵션을 추가할 수 있다.

또한 기존에 사용하던 컴포넌트를 확장할 수도 있는데

const Hello = styled.div`
    width: 200px;
    height: 100px;
`

const ColorHellp = styled(Hello)`
    background-color: orange;
`

이런 식으로 기존에 사용하던 컴포넌트를 확정해서 사용할 수 있다.


2. 유연한 css 적용

선언된 styled-components들이 부모 자식 요소로 섞여 있는 경우를 종종 볼 수 있다.
퓨어 css에서는 스코프 안에 선택자 스코프로 처리를 하는데, styled-components에서는 어떻게 처리해야할까??

예시

const HelloCss = () => {
    return (
        <>
            <HelloBind>
                <Hello>안녕하세요</Hello>
                <ColorHello>주황 배경입니다.</ColorHello>
            </HelloBind>
            <ColorHello>주황 배경입니다.</ColorHello>

        </>
    )
}


const HelloBind = styled.div`
    width: 500px;
    height: 500px;
    border: 2px solid red;
`

const Hello = styled.div`
    width: 200px;
    height: 100px;
`

const ColorHello = styled(Hello)`
    background-color: orange;
`

이러한 상황에서 HelloBind 안의 ColorHello는 background-color를 red로 바꾸고 싶을 수 있다.
여기서 우리는 HelloBind의 하위요소인 ColorHello만을 선택해서 css를 적용할 수 있다.

const HelloBind = styled.div`
    width: 500px;
    height: 500px;
    border: 2px solid red;
    ${Memo} {
      background-color: red;
    }
`
${} {

}

이와 같이를 우리는 부모 요소 아래의 컴포넌트를 수정할 수 있다.


3. props를 이용한 css 적용

같은 태그를 가진 element의 css가 중복될 경우 props를 통해 유연한 값을 설정해 줄 수 있다.

예시

const Exam = () => {
    return (
        <>
            <Test  />
            <TestBox />
        </>
    )
}

const Test = styled.div`
    width: 300px;
    height: 500px;
    border: 2px solid red;
    background-color: blue;
`

const TestBox = styled.div`
    width: 300px;
    height: 500px;
    border: 2px solid red;
    background-color: green;
`

위에 코드에서 Test와 TestBox는 background-color 속성만 다르고 나머지는 일치하는 상황을 볼 수 있다.
이러한 경우 현재처럼 Test와 TestBox를 만들지 말고 background-color의 색상을 props로 전달하면 된다.

const Exam = () => {
    return (
        <>
            <Test backgroundColor="blue" />
            <Test backgroundColor="green" />
        </>
    )
}

const Test = styled.div`
    width: 300px;
    height: 500px;
    border: 2px solid red;
    background-color: ${(props) => props.backgroundColor};;
`

이런 식으로 이제는 한 컴포넌트 안에서 속성 값을 props로 받아 코드의 중복을 막을 수 있다.


오늘은 평소 유용하게 사용하던 styled-component를 정리해 보았다.
css 만큼은 자신 있었지만 이렇게 한 번 정리를 하니 더 효율적으로 코드를 짤 수 있을 것 같다는 생각이 들었다.

profile
프론트엔드 개발자를 꿈꾸고 있습니다. 감사합니다.

0개의 댓글