FRONT/REACT

[React] Styled Component 사용하기

연듀 2022. 1. 19. 16:09
노마드코더 React JS 마스터 클래스 #2 STYLED COMPONENTS

 

 

 

npm i styled-components

 

로 styled-components를  설치해준다. 

 

 

import styled from "styled-components";

function App() {
  return (
    <div style={{ display: "flex" }}>
      <div style={{ backgroundColor: "teal", width: 100, height: 100 }}></div>
      <div style={{ backgroundColor: "tomato", width: 100, height: 100 }}></div>
    </div>
  );
}

export default App;

 

 

기존의 코드는 태그 안에 일일히 style을 지정해주는 것이였다.

 

 

styled component 사용하면 className이나 style을 사용할 필요가 없다. 

styled component에서 import한 styled를 이용한다. 
div를 사용해 닫아줄 필요가 없다.
모든 style은 컴포넌트를 사용하기 전에 미리 컴포넌트에 포함된다. 

css코드를 css 방식 그대로 쓸 수 있다. 

 

 

styled component를 사용한 코드는 아래와 같다. 

 

import styled from "styled-components";

const Father = styled.div`
  display: flex;
`;

const BoxOne = styled.div`
  background-color: teal;
  width: 100px;
  height: 100px;
`;

const BoxTwo = styled.div`
  background-color: tomato;
  width: 100px;
  height: 100px;
`;

const Text = styled.span`
  color: white;
`;

function App() {
  return (
    <Father>
      <BoxOne>
        <Text>Hello</Text>
      </BoxOne>
      <BoxTwo />
    </Father>
  );
}

export default App;

 

 

 

브라우저를 보면 아까와 같이 동작하고, styled components가 클래스명을 만들어 준다.