꾸준히 성장하는 개발자

[react] styled-component 정리하기 본문

React

[react] styled-component 정리하기

ahleum 2022. 2. 8. 01:20

스타일을 자동으로 넣어주고 클래스네임도 자동으로 넣어주는 기능

최대한 오염이 되지 않는 스타일을 먹일수 있는 좋은 방법이다.

 

터미널에 작성하여 install 해준다.

npm i styled-components

 

설치가 다 되었으면 사용해보자

 


 

 

사용하는 방법으로 

         <StyledButton>버튼</StyledButton>
import styled from 'styled-components';

const StyledButton =styled.button`
background : transparent;
border-radius:3px;
border:2px solid palevioletred;
color: palevioletred;
margin: 0 1em;
padding: 0.25em 1em;
font-size:20px;
`;

export default StyledButton;

`` 템플릿 사이에 css 작성하듯 작성하여 style을 넣어줄 수 있다.

 

 


 

<StyledButton>버튼</StyledButton>
<StyledButton primary>버튼</StyledButton>
import styled,{css}  from 'styled-components';

const StyledButton =styled.button`
background : transparent;
border-radius:3px;
border:2px solid palevioletred;
color: palevioletred;
margin: 0 1em;
padding: 0.25em 1em;
font-size:20px;

${props => 
    props.primary && 
    css`
    background :palevioletred;
    color:white;
 `}
`;

${props =>

    props.primary &&
    css`
    background :palevioletred;
    color:white;
 `}                                          primary라는 props를 전달받아  
                                             그 디자인에 맞는 스타일을 넣어줄수 있다.

 

 


있는 컴포넌트에 스타일을 더 넣어서 새로운 컴포넌트 만들기

 

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

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

                      ↓    이렇게 변경이 가능하다

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

const Circle = styled(box)`
  border-radius: 50px;
`;
 
 
 
const Circle = styled(Box)`    //기존에 있는 styled에 인자로 Box을 넣고 
  border-radius: 50px;          //추가로 스타일을 넣어준다. 
`;
   

 


 
styled components가 컴포넌트를 생성할 때, 속성 값을 설정할 수 있게 해준다.

 

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

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

const Input = styled . input . attrs({ required: true, minlength: 10 })`

  background-color: tomato;
`;

 


 animation주기 - helper function을 import 해준다

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

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

const animation = keyframes`
 from{
   transform: rotate(0deg);
   border-radius: 0px;
 }to{
   transform: rotate(360deg);
   border-radius: 100px;
 }
 `;
 
 // 0% 50% 100% 이런식으로도 넣을 수 있다 
 
 const Box = styled.div`
  height: 200px;
  width: 200px;
  background-color: tomato;
  animation: ${animation} 1s linear infinite;
`;
 
 function App() {
  return (
    <Wrapper>
      <Box />
    </Wrapper>
  );
}

 

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

 


컴포넌트 안의 태그를 선택하여 스타일을 더 넣어줄 수 있다

const Box = styled.div`
  height: 200px;
  width: 200px;
  background-color: tomato;
  display: flex;
  justify-content: center;
  align-items: center;
  span {
    font-size: 36px;
  }
`;

 function App() {
  return (
    <Wrapper>
      <span>😁</span>
    </Wrapper>
  );
}

 

const Box = styled.div`
  height: 200px;
  width: 200px;
  span {
    font-size: 36px;

  }
`;

 

만약 컴포넌트를 넣어주기를 원한다면 ${컴포넌트} 로 작성해주면 된다.

const Emoji = styled.div`
	font-size : 20px
`

const Box = styled.div`
  height: 200px;
  width: 200px;
  background-color: tomato;
  display: flex;
  justify-content: center;
  align-items: center;
  ${Emoji} {
    font-size: 36px;
  }
`;

 function App() {
  return (
    <Wrapper>
      <Emoji>😁</Emoji>
    </Wrapper>
  );
}
 
위처럼 넣어줄 컴포넌트를 ${ }로 감싸서 작성해주면 된다
 
${Emoji} {
    &:hover {
      font-size: 90px;
    }

 

 


 

const Box = styled.div`
  height: 200px;
  width: 200px;
  span {
    font-size: 36px;
    &:hover {
      font-size: 42px;
    }
     &:active{
      opacity: 0;
    }
  }
`;

 

 :hover 효과 같은 가상클래스 선택자를 넣어줄 수 있다.

const Box = styled.div`
  height: 200px;
  width: 200px;
  span {
    font-size: 36px;
    & : hover {                                //여기서 &는 앞의 선택자인 span을 뜻한다 span:hover
      font-size: 42px;
    }

     & : active {
      opacity: 0;
    }

  }
`;

 

위처럼 가상 클래스 선택자를 넣어줄 태그안에 

& : hover{ }  이렇게 넣어주면

span : hover{ } 이렇게 작성하는 것과 같다


 
현재는 button이지만
as라는 props를 이용하여 다른 태그(ex. <a>태그)처럼 만들어줄수 있다. 
 
 
<StyledButton as="a" href="/">버튼</StyledButton>

 


as를 또 이용해보자

 

다른 기능이나 스타일을 가진 button에 다른 스타일을 적용해주고 싶다면 아래처럼

as에 component를 지정해서 적용시킬 수 있다.

import logo from './logo.svg';
import './App.css';
import StyledButton from './components/StyedButton';

const UppercaseButton = (props) =>(
<button {...props} children={props.children.toUpperCase()}/>
);

function App() {
  return (
    <div className="App">
      <GlobalStyle />
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>        
         <StyledButton as={UppercaseButton}>button</StyledButton> 
          {/* as를 사용하여 임시로 stlye을 땡겨서 특정 component에 style을 넣어줄수 있다 */}
       </p>
      </header>
    </div>
  );
}

export default App;

 


as를 쓰는 방법보다 더 일반적인 방식으로는 

component를 이용하여 스타일을 넣어줄 수 있다.

 

 

import logo from './logo.svg';
import './App.css';
import StyledButton from './components/StyedButton';
import styled, {createGlobalStyle} from "styled-components";
import StyledA from './components/StyledA';

// const MyButton =(props)=>(
//   <button {...props} children={`MyButton ${props.children}`} />
// );

const MyButton =(props)=>(
  <button className={props.className} children={`MyButton ${props.children}`} />
);

const StyledMyButton=styled(MyButton)`
  background : transparent;
  border-radius:3px;
  border:2px solid ${(props)=>props.color || "palevioletred"};
  color: ${(props)=>props.color || "palevioletred"};
  margin: 0 1em;
  padding: 0.25em 1em;
  font-size:20px;

  :hover{
    border: 2px solid red;
  }

  ::before{
    content: "@";
  }
`;


function App() {
  return (
    <div className="App">
      <GlobalStyle />
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>        
         <StyledMyButton>Button</StyledMyButton> 
         <StyledMyButton color="green">Button</StyledMyButton>
         <StyledA href="https://google.com">태그</StyledA>
       </p>
      </header>
    </div>
  );
}

export default App;

 

주의할 점!!

 
const MyButton =(props)=>(
  <button {...props} children={`MyButton ${props.children}`} />   
);
 

        ↓        {...props}   ->  className={props.className}  로 바꿔야 문제가 없다 

 
const MyButton =(props)=>(
  <button className={props.className} children={`MyButton ${props.children}`} />
);

왜냐하면 styled component가 element에 className을 추가해주고 있는 것

그렇기 때문에 styled component가 추가해준 className을 component를 통해 다시 element에 전달하는 작업을

해줘야 할 필요가 있다.

 

 


 

props를 받아서 뭔가 표현해주는 방식을 component에서도 할 수 있다.

border:2px solid ${(props)=>props.color || "palevioletred"};
color: ${(props)=>props.color || "palevioletred"};
<StyledMyButton color="green">Button</StyledMyButton>

props가 있으면 그 값으로 없다면 "palevioletred" 색상으로 표현한다

 


 

 

이렇게 쓰게 되면 전역적인 스타일을 넣기 힘들 수 있는데 

그래서 글로벌로 스타일을 넣어줄 수 있다.

import logo from './logo.svg';
import './App.css';
import StyledButton from './components/StyedButton';
import styled, {createGlobalStyle} from "styled-components";
import StyledA from './components/StyledA';



const GlobalStyle = createGlobalStyle`
button{
  color:yellow;
}
`;


function App() {
  return (
    <div className="App">
    // 어디선가 render 되는것이 필요함 항상 글로벌한 부분에서 render되도록 해주자
      <GlobalStyle />
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
         <StyledButton>버튼</StyledButton>
         <StyledButton primary>버튼</StyledButton>
         <PrimaryStyledButton>버튼</PrimaryStyledButton>
         <StyledButton as="a" href="/">버튼</StyledButton>
         <StyledButton as={UppercaseButton}>button</StyledButton> 
         {/* as를 사용하여 임시로 stlye을 땡겨서 특정 component에 style을 넣어줄수 있다 */}
         <StyledMyButton>Button</StyledMyButton> 
         <StyledMyButton color="green">Button</StyledMyButton>
         <StyledA href="https://google.com">태그</StyledA>
       </p>
      </header>
    </div>
  );
}

export default App;

const GlobalStyle = createGlobalStyle`
button {
  color:yellow;
}
`;

'React' 카테고리의 다른 글

[react] Ant Design  (0) 2022.02.10
[react] react-shadow  (0) 2022.02.09
React-Router-Dom v6 되며 바뀐 점 정리  (1) 2022.01.24
react의 라우팅  (0) 2022.01.24
husky , lint-staged  (0) 2022.01.23