React/노마드코더 React_Master

[ReactMaster] Styled components

seung_hyeon 2024. 7. 23. 14:07

#2 Styled components

 

styled components 설치

npm i styled-components

+) npm start 안될 경우 cd my-app 

 

 

 

styled components

className, style 사용할 필요 없다(알아서 만들어 준다)

 

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

function App() {
  return (
    <Father />
  )
}

 

styled.태그명` (유효한 html 태그만 가능)

백틱 안 css

`;

 

 

1. props 이용하여 컴포넌트 설정

const Box = styled.div`
background-color : ${(props) => props.bgColor};
width: 100px;
height: 100px;
`;

function App() {
  return (
    <Father>
    <Box bgColor="teal"/>
    <Box bgColor="tomato"/>
    </Father>
  )
}

 

 

2. 컴포넌트 확장

const Box = styled.div`
background-color : ${(props) => props.bgColor};
width: 100px;
height: 100px;
`;

const Circle = styled(Box)`
  border-radius: 50px;
`;

 

Box의 모든 속성을 Circle에 넣음

→ 기존의 속성 + 새로운 속성

 

 

 

• styled components 이용한 트릭

 

1.  태그 바꾸기

const Btn = styled.button`
  color: white;
  background-color: tomato;
  border: 0;
  border-radious: 15px;
`;

const Link = styled(Btn)`
`;
function App() {
  return (
    <Father>
    <Btn>Log in</Btn>
    <Btn as="a" href="/">Log in</Btn>
    </Father>
  )
}

➣ as 사용하여 태그 바꾸기 가능

 

 

2. html 태그의 속성 설정

const Input = styled.input.attrs({required: true, minLengt:"10"})`
  background-color: white;
`;

function App() {
  return (
    <Father>
      <Input />
      <Input />
      <Input />
      <Input />
    </Father>
  )
}

➣  asttrs

input으로 전달된 모든 속성을 가진 오브젝트를 담을 수 있다

콘솔창

 

 

 

• animation

import styled, {keyframes} from "styled-components";

const animantion = keyframes`
from {
  transform:rotate(0deg);
}
to{
  transform:rotate(360deg);
}
`;

const Box = styled.div`
height: 200px;
width:200px;
background-color: tomato;
animation:${animantion} 1s linear infinite;
`;

 

➣ helper function(keyfrmes)을 import

from 시작 - to 끝

ex) 0%, 50%, 100%

 

 

- target 처리

const Box = styled.div`
  height: 200px;
  width:200px;
  background-color: tomato;
  display: flex;
  justify-content: center;
  align-items: center;
  animation:${animantion} 1s linear infinite;
  span {
  font-size: 36px;
}
`;
function App() {
  return (
    <Wrapper>
      <Box>
        <span>🐯</span>
      </Box>
    </Wrapper>
  )
}

box 안에 있는 span 선택

span은 styled component가 아니다

→ 부모(Box)로부터 선택 가능

 

 

 

- pseudo selector

styled 안에 있는 걸 select 

ex) :hover, :active...

hover: 마우스를 특정 요소 위에 올렸을 때 적용되는 스타일

active: 요소를 클릭하고 있는 동안 적용되는 스타일

&:hover{
  font-size: 40px;
}

^ / & 사용

 

 

 

• styled component 안의 element 선택

const Emoji = styled.span`
  font-size: 36px;
`;

const Box = styled.div`
  height: 200px;
  width:200px;
  background-color: tomato;
  display: flex;
  justify-content: center;
  align-items: center;
  animation:${animantion} 1s linear infinite;
  ${Emoji}:hover{
    font-size: 98px;
  }
}
`;

function App() {
  return (
    <Wrapper>
      <Box>
        <Emoji>🐯</Emoji>
      </Box>
    </Wrapper>
  )
}

이모지 컴포넌트 지목

 

themes

다크모드 구현 : 50% - theme / 50% - local Estate Management

theme: 기본적으로 모든 색상들을 가지고 있는 object

<index.js>

import {ThemeProvider} from "styled-components";

const darkTheme ={
   //사용할 색상
   tectColor: "whitesmoke",
   backgroundColor: "#111",
};

const lightTheme ={
  //사용할 색상
  tectColor:"#111",
  backgroundColor: "whitesmoke",
  };

ReactDOM.render(
  <React.StrictMode>
    <ThemeProvider theme={darkTheme}>
    <App />
    </ThemeProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

➣ object를 ThemeProvider 준다

두 개의 theme이 동일한 property 이름 가지고 있으면 theme 전환할 때 component 따로 바꿀 필요 없다

 

<App.js>

import styled, { keyframes } from "styled-components";

const Title = styled.h1`
  color: ${(props) => props.theme.textColor};
`;

const Wrapper = styled.div`
  display: flex;
  height: 100vh;
  width: 100vw;
  justify-content: center;
  align-items: center;
  background-color: ${(props) => props.theme.backgroundColor};
`;

function App() {
  return (
    <Wrapper>
     <Title>Hello</Title>
    </Wrapper>
  )
}

App ThemeProvider 안에 있기 때문에 App component들이 색에 접근 가능

 

 

 

• 총 정리

- div 만든 후 className, style 부여  →  styled component 사용

- styled component : styled. 사용할 html 태그 이름`css코드`;

- component 설정 → props를 인자로 받아 컴포넌트에 전달해 줄 함수 만들기

- component의 모든 요소 유지 + 새로운 코드 추가 → styled.( )

- html 태그 바꾸기 → prop 추가 (as = "a")

- 속성이 반복되는 component 같은 attribute 가져야 한다 →. attrs( ) 추가

- animation : 받을 element + 그 animation 만들기 / keyframes helper 사용

- pseudo selector: styled 안에 있는 걸 select 

- styled component안에 있는 styled component  select

'React > 노마드코더 React_Master' 카테고리의 다른 글

[ReactMaster] TypeScript  (1) 2024.07.24