This is it. it's IT.

React - Styled component 사용하기 본문

Frontend/React.js

React - Styled component 사용하기

응애개발자 애기 2022. 4. 1. 15:56
728x90
반응형
npm i styled-components

 

터미널에 입력한다. 

그러면 스타일 컴포넌트와 관련된 것들을 다운로드 받을 수 있다. .. . 

 

 

import styled from "styled-components";

App.js 상단에 import해서 가져와준다. 

 

import styled from "styled-components";

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

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

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


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

export default App;

이런 식으로 스타일드 컴포넌트를 삽입하여 css에 대한 가독성을 높힐 수 있따. 

 

하지만!! 

비슷하지만 값이 하나씩 다른 컴포넌트들에 대해서는 어떻게 처리를 해야할까??

계속 새로운 컴포넌트를 생성해야하는 걸까?>??

아니다!!!!!!!!

 

가변적인 값을 넣어주기 위해서는 , props를 이용하면 손쉽게 문제를 해결할 수 있따. 

(props : 속성)

 

import styled from "styled-components";

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

const Box = styled.div`
  background-color: ${(props) => props.bgColor}; // 바로 이런 식으로 props 안에 변수를 지정하는 거시당
  height: 100px;
  width: 100px;
`;


function App() {
  return (
    <Father>
      <Box bgColor="teal"/> <- props를 통해 만들어진 변수에 값을 다르게 넣으면 됩니당
      <Box bgColor="tomato"/>
    </Father>
  );
}

export default App;

 

 

결과물

 

 

 

한가지 더 ! 

스타일 컴포넌트를 확장시킬 수도 있따. 

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

이런 식으로 새로운 스타일컴포넌트에게 기존 컴포넌트의 속성을 전부 상속?시킬 수 있는 것이다. 

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

 

결과물

굿잡^^ width와 height의 내용이 확장되어서 자동으로 Circle이 부피를 갖게 되었어. 

 

그런데 만약 div태그를 a태그로써 사용하여 링크의 역할을 하게 하고 싶다면?

 

      <Box as="a" bgColor="teal"/>

as="a" 를 삽입하면 된다규. 

모든 특정 html 요소를 다른 요소로 바꾸어 사용할 수 있게 도와줄 것이야. 

이렇게 적은 뒤 웹서버로 호스팅하고 inspect 해보면,

처음엔 div로 생성했지만 a태그로 생성된 것을 알 수 있서 ^^

 

분석

 

attrs

그리고...

attrs를 쓰면, 스타일 외의 html요소 고유의 속성도 스타일컴포넌트에서 통제할 수 있어!!! 

html태그를 중복해서 쓰지 않아도 되는 고징 ^.^

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

attrs({이 안에 html요소에 들어갈 속성을 넣으면 된단다~~~~~})

이렇게 한 뒤에 랜더링을 해보면... (F12 눌러서 확인!!)

 

input에 required, minlength 속성이 들어있ㄴ느 것을 볼 수 있어~~~

와! 정말 편리하겠는 걸!!! 재사용성이 좋아질 것 같아. ㅎㅎ

 

 

Animation

그럼 애니메이션을 만들 때는!> 어케 할까? ㅎㅎ

 

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

우선 keyframes 를 임포트 할 필요가 있어. ㅎ 애니메이션 만들 때 꼭 필요하뉘까~~~~ㅎ

 

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

const Father = styled.div`
  display: flex;
`;
const animation1 = keyframes`
  from{
    transform: rotate(0deg);
  }
  to{
    transform: rotate(360deg);
  }
`; // 키프레임을 이용하여 360도 회전하는 애니메이션을 정의했다. 
const Box = styled.div`
  background-color: tomato;
  height: 200px;
  width: 200px;
  animation: ${animation1} 1s linear infinite; //변수의 이름과 동일하게!
`; // animation을 추가하여 Box가 360도 회전하도록 해주었다. 
function App() {
  return (
    <Father>
      <Box/>
    </Father>
  );
}

export default App;

그럼 회전하는 도형을 볼 수 있을 거야 ~~

참고로 from{} to{} 로 정의되는 애니메이션 효과는

% 퍼센테이지로도 지정이 가능해~~~ 0%{} 50%{} 100%{} 이런식으루 말이야 ^^

 

 

Pseudo Selector

그리고, 만약 Box 안에 자식 요소가 들어간다고 치면...

Box안에 들어갈 자식 요소들에 대한 스타일을 미리 지정해줄 수 잇다!!

const Box = styled.div`
  background-color: tomato;
  height: 200px;
  width: 200px;
  display: flex;
  align-items: center;
  animation: ${animation1} 1s linear infinite; //변수의 이름과 동일하게!
  span{
    font-size: 36px;
    &:hover{
      font-size: 42px;
    }//바로 이런 식으로 지정할 수가 있다. 심지어 hover까지! &은 this라는 뜻이야 아마
  }
`;

이렇게 하면 나중에 Box 컴포넌트 안에 들어오는 span태그인 자식요소는 font-size가 36px이 되겠지 ^.^

그리고 span에다가 hover를 하면 42px로 바뀔거고 말이야~~

 

만약, pseudo selecter로 html태그가 아닌 스타일컴포넌트 자체를 지정한다면, 

${ } 안에 컴포넌트의 이름을 넣어서 적용해야 해~~~

 

 

 

Theme

import { ThemeProvider } from 'styled-components';

Theme을 제공하는 기능을 import

const darkTheme={
  textColor:"whitesmoke",
  backgroundColor:"#111",
};

const lightTheme={
  textColor:"#111",
  backgroundColor:"whitesmoke",
};

각각의 theme을 정의해준다

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

어떤 Theme로 출력할지 정함 ㅇㅅㅇ ThemeProvider가

const Box = styled.div`
  color: ${(props) => props.theme.textColor};
  background-color: ${(props) => props.theme.backgroundColor};
  
  	...중략
  `;

Theme의 컬러를 받아올 때는 props 안에서 각각의 속성의 값으로 받아옴 ㅇㅅㅇ

그렇기 때문에 테마를 만들 때 테마의 속성을 각 테마마다 일치시켜서 만들어야함.

 

 

 

 

+++++++++

참고로 react의 styled component에서는 css구문 자동완성이 안된다...

그러므로 

'vscode-styled-components' 라고 vscode의 마켓플레이스에 검색해서

익스텐션을 설치해주어야 한다. 

 

그러면 쾌적한 환경에서 css코딩을 할 수 있을 것이당 ^^

 

 

 

 

 

 

노마드 코더 강좌를 참고했습니다

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

728x90

'Frontend > React.js' 카테고리의 다른 글

react 단축키  (0) 2022.06.09
TypeScript를 리액트 프로젝트에 적용  (0) 2022.04.01
React 프로젝트 생성 시 보안오류 문제 해결  (0) 2022.04.01
UseState 함수  (0) 2022.03.31
React의 기초  (0) 2022.03.29
Comments