본문 바로가기

React

[React] Styled Components

styled-components 를 사용하기 위해서는 다음과 같은 패키지를 설치한다.

yarn add react styled-components

 

 

1. css in JS : 자바스크립트로 css 코드를 작성하는방식 

style component를 styled.태그 형태로 다음과 같이 작성하고 확인해보면

import "./App.css";
import styled from "styled-components";

const StBox = styled.div`
  width: 100px;
  height: 100px;
  border: 1px solid red;
  margin: 20px;
`;

function App() {
  return <StBox>박스</StBox>;
}

export default App;

스타일이 잘 적용 된 것을 확인할 수 있다. 또한 이렇게 만들어진 컴포넌트는 실제 태그 <StBox></StBox> 처럼 사용할 수 있다. 

 

const StP = styled.p`
  color: blue;
`;
function App() {
  return (
    <StBox>
      <StP>나는 p태그 입니다.</StP>
    </StBox>
  );
}

2. props를 통해서 부모 -> 자식으로 조건부 스타일링 가능

다음처럼 props 를 활용해서 부모-> 자식으로 스타일 요소를 내려줄 수도 있다.

import "./App.css";
import styled from "styled-components";

const StBox = styled.div`
  width: 100px;
  height: 100px;
  border: 1px solid ${(props) => props.borderColor};
  margin: 20px;
  background-color: ${(props)=> props.backgroundColor};
`;

function App() {
  return (
    <>
      <StBox borderColor="red" backgroundColor="yellow">
        빨간박스
      </StBox>
      <StBox borderColor="blue">파란박스</StBox>
      <StBox borderColor="green">초록박스</StBox>
    </>
  );
}
// props : 부모 -> 자식으로 내려주는 데이터

export default App;

 

[리팩토링]

// 박스의 색
const boxList = ["red", "blue", "green", "black"];

// 색을 넣으면, 이름을 변환
const getBoxName = (color) => {
  switch (color) {
    case "red":
      return "빨간 박스";
    case "blue":
      return "파란 박스";
    case "green":
      return "초록 박스";
    default:
      return "검정 박스";
  }
};

function App() {
  return (
    <StContainer>
      {boxList.map((box) => {
        return <StBox borderColor={box}>{getBoxName(box)}</StBox>;
      })}
    </StContainer>
  );
}

'React' 카테고리의 다른 글

[React] React Hooks (useContext)  (0) 2023.06.20
[React] React Hooks (useRef)  (0) 2023.06.20
[React] React Hooks (useEffect), clean up  (0) 2023.06.19
[React] React Hooks (useState)  (0) 2023.06.19
[React] map 메소드 적용/ 오류 해결  (0) 2023.06.14