본문 바로가기

sparta/REACT

[REACT] 숙련주차 - styled-components

세팅
npm add styled-components

제일 먼저 터미널에서 적고 기다리면 패키지가 설치되었다는 문구가 뜰 거다.

 

이후에는 extends에서styled-Components Extractor 설치!

import styled from "styled-components";

맨위에 코드를 적어주면 세팅 완료.

 

 


기본
const App = () => {
  return (
    <>
      <h1
        style={{
          color: "blue",
        }}
      >
        Hello world!
      </h1>
      <p className="sample">This is a simple app</p>
    </>
  );
};

위 코드처럼 객체형태로 style안에 적으면 되는데 좀더 재밌는 코드를 배웠다.

 

 

리팩토링 적용
* key 속성은 각 요소에 고유한 값을 부여하여 React가 어떤 요소가 변경되었는지, 추가되었는지, 삭제되었는지를 쉽게 알아볼 수 있도록 도와준다.

 

import styled from "styled-components";
//컴포넌트는 반드시 대문자로 시작해야 동작함.


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

//배열로 색 지정.
const boxList = ["red", "green", "blue"];
const getBoxName = (color) => {
  switch (color) {
    case "red":
      return " 빨간박스";
    case "green":
      return "초록박스";
    case "blue":
      return "파란박스";

    default:
      return "검정박스";
  }
};
function App() {
  return (
    <>
      {boxList.map((boxColor) => {
        return (
        //[ "red", " green ", "blue" ] 각각의 StBox는 key로 "red", "blue", "green"을 가진다.
          <StBox key={boxColor} borderColor={boxColor}>
            {getBoxName(boxColor)}
          </StBox>
        );
      })}
    </>
  );
}

 

 

'sparta > REACT' 카테고리의 다른 글

[REACT] 타임어택(스탠다스)  (3) 2024.11.07
[REACT] useEffect, useRef 기본구조  (0) 2024.11.04
[REACT]  (1) 2024.11.01
[REACT] React Hooks  (0) 2024.10.31
[REACT] PROPS(Read-Only)2  (0) 2024.10.30