• React

[React] styled-components / SASS / CSS Module

man_on 2021. 10. 24. 22:30
반응형

 

 

 

 

     


     

    React에서의 스타일링

     

    - css

    - css.module

    - styled component

    - scss

     

     

     

     

    styled-component  

     

     

    🔻사용이유

     

    컴포넌트가 많은 경우 스타일링에 불편함이 발생한다.

    1. class 중복으로 생성한다.

    2. 다른 컴포넌트에 원하지않는 스타일이 적용된다.

    3. css파일이 너무 길어져서 수정이 어렵다.

     

    > 컴포넌트 제작 시 styled-components라는 라이브러리를 이용하여 js파일에서 스타일을 바로 입힌다.

       컴포넌트마다 고유한 클래스를 가진다.

     

     

     

     

    🔻 설치

    yarn add styled-components
    npm install styled-components
    //1.import 한다.
    import styled from "styled-components";
    
    
    //2.styled.만들고싶은태그 적고 백틱안에 원하는 스타일 넣어준다.
    let 스타일 = styled.div`
      pdding: 20px;
      margin-left: 10px;
      font-size: 300px;
    `;
    
    function Detail () {
      <스타일> hello </스타일>
    }

     

     

    ✔️ Image

    const LogoImg = styled.img.attrs({
      src: "https://static.wanted.co.kr/images/icon-menu.png",
      alt: "hamberger menu",
    })`
      width: 17px;
      height: 14px;
      cursor: pointer;
    `;

     

     

     

     

    https://styled-components.com/docs/basics

     

    styled-components: Basics

    Get Started with styled-components basics.

    styled-components.com


     

     

     

    props

     

    // 백틱기호 안에서 문자 중간에 함수나 변수 집어넣고 싶을때 ${} 안에 써준다. 콜백함수로 넣어야한다.
    let 스타일 = styled.div`
      pdding: 20px;
      color : ${ props => props.색상 };
    `;
    
    
    function Detail () {
     return (
       <div>
         <스타일 색상="blue"> hello </스타일>
         <스타일 색상={'red'}> hello </스타일>
    }

     

     

    ✔️ Button

    const Button = styled.button`
     border-radius : 50px;
     cursor : pointer;
     &:active,
     &:focus {
      outline : none;
     }
     background-color : ${props=> (props.danger ? "red" : "green")};
    `;
    
    <Button />            // green
    <Button danger />     // red

     

     

     

     


     

     

     

     

    extend / mixin

     

     

     

    1. extend

    const Button = styled.button`
     border-radius : 50px;
     cursor : pointer;
     &:active,
     &:focus {
      outline : none;
     }
     background-color : ${props=> (props.danger ? "red" : "green")};
    `;
    
    
    //작동안함
    const Anchor = Button.withComponent("a").extend`
     text-decoration : none;
    `;
    
    //구글검색!!
    const Anchor = styled(Button.withComponent("a"))`
     text-decoration : none;
    `;

     

     

    2. mixin

    import styled, { css } from "styled-components";
    
    const awesomeCard = css`
     box-shodow : 0 4px 6px rgba(50,50,93,0.11);
     padding: 20px;
    `;
    
    const Container = styled.div`
     height : 100px;
     width : 100%
    `;
    
    const Input = styled.input.attrs({
     required: true
    })`
     border : none;
     ${awesomeCard};
    `;

     

     

     


     

     

     

    Theme

     

     

     

    Theming

    모든파일에서 공통으로 사용하고 싶은 속성을을 위해서 theme.js파일 생성한다. 

    // theme.js
    
    const theme = {
     mainColor : "#454545",
     dangerColor : "red",
     successColor : "blue"
    };
    
    export default theme;

     

     

    적용하고싶은 파일에 import해와서 적용시켜준다.

    import styled, { ThemeProvider } from "styled-components";
    import theme from "./theme"
    
    
    class App extends Component {
     render() {
      return (
       <ThemeProvider theme={theme}>
        <Container>
         <Form>
          ...
       <ThemeProvide />
    }
    
    const Form = () => {
     <Card>
      <Button />
      ...
      
      
    const Button = styled.button`
     background-color : ${props => props.theme.dangerColor};
    `;

     

     


     

     

     

    Nesting

     

     

     

     > container안에 모든 Card 컴포넌트를 선택하고싶을 때

    class App extends Component {
     render() {
      return (
       <ThemeProvider theme={theme}>
        <Container>
         <Form>
          ...
       <ThemeProvide />
    }
    
    const Form = () => {
     <Card>
      <Button />
      ...
      
      
    const Container = styled.div`
      height : 100px;
      ${Card} {
       background-color : red;
     }
    `

     

     

     

     

     

     

     

     

     

     

     

    SASS 

     

     

     

     : css를 프로그래밍언어스럽게 작성가능한 preprocessor

      브라우저는 sass문법 모르니까, sass로 작성한 파일을 다시 css로 컴파일해야한다. (node-sass가 그거해줌)

     

     

    yarn add node-sass
    npm install node-sass

     

    > 파일명을 .scss로 하고 import해준다.

    import './Detail.scss';

     

     

    sass를 사용하는 이유

     

    1. 변수를 사용한다.

      $변수명 : 집어넣을값;

    $maincolor: red;
    
    
    div {
      color: $maincolor;
    }

     

     

    2. @import

      다른 scss파일에서 쓰 import해서 가져와쓴다.

    /*  reset.scss  */
    
    $lightGray: #f2f2f3;
    $fontColor: #323d45;
    $white: #ffffff;
    $sky: #00b8ff;
    $navy: #02469d;
    /*  지정할 scss파일에 import해준다.  */
    
    @import "./reset.scss";
    
    .CardWrap {
      border: 1px solid $lightGray;
      border-radius: 4px;
      color: $fontColor;
    }

     

     

     

     

    3. nesting 문법

      : 셀렉터 해석쉽고, 관련된 class끼리 뭉텅이로 관리가 편하다.

    div.container h4 {
      color : blue;
    }
    div.container p {
      color : green;
    }
    /* nesting */
    
    div.container {
      h4 {
        color : blue;
      }
      p {
        color : green;
      }
    }

     

     

     

    4. extends 문법

      비슷한 css있을때 복붙말고 extend로 가져와서 재활용한다.

    .my-alert {
      background : #eeeeee;
      padding : 15px;
      border-radius : 5px;
      max-width : 500px;
      width : 100%;
      margin : auto;
    }
    
    /* extend로 그대로 가져와서 color만 바꿔준다. */
    
    .my-alert2 {
      @extend .my-alert;
      background : yellow;
    }

     

     

     

     

    5. @mixin /@include 

     함수만드는 문법이다. function대신 @mixin이라고 쓰고 중괄호안에 축약하고 싶은 코드들을 담으면된다.

     불러올때는 @include 함수명()으로 불러온다.

     

     * 함수명이 위에 선언되어 있어야 밑에서 사용가능하다.

     

    @mixin 함수() {
      background : #eeeeee;
      padding : 15px;
      border-radius : 5px;
      max-width : 500px;
      width : 100%;
      margin : auto;
    }
    .my-alert {
      @include 함수()
    }

     

     

     

    https://sass-lang.com/guide

     

    Sass: Sass Basics

    Before you can use Sass, you need to set it up on your project. If you want to just browse here, go ahead, but we recommend you go install Sass first. Go here if you want to learn how to get everything set up. Preprocessing CSS on its own can be fun, but s

    sass-lang.com

     

     


     

     

     

     

     

     

    CSS  Module

     

     

    🔻 사용이유?

        :  component를 스타일링 할 대 css클래스가 중첩되는 것을 방지할 수 있다.

     

     

    ✔️ 사용법

     

    1. 확장자를 .module.css 로 한다.

    Box.module.css

    .Box {
      background: black;
      color: white;
      padding: 2rem;
    }

     

     

    2. import로 불러온 객체안에 있는 값을 참조한다.

    import React from "react";
    import styles from "./Box.module.css";
    
    function Box() {
      return <div className={styles.Box}>{styles.Box}</div>;
    }
    
    export default Box;

     

     

    classname이 고유한값이 할당된다.

     

     

     

     

     

     

     


     

     

     

     

     

     

    Media Query

     

     

     

    @media only screen and (max-widthh: 480px) {
    	body {
        		font-size : 12px;
       }
    }

    @media

       : media 쿼리를 시작

    only screen

       : 어떤 디바이스에서 적용하는지 알려준다. screen이라고 할 경우 어떤 디바이스에 상관없이, 화면에 보이는 스크린이면 전부 적용된다.

          ex) 프린트 하고 싶을 때 적용하려면 only print                  

    and (max-width : 480px)

       : media feature - 어느 조건에 아래의 css를 적용할지 작성한다.

     

     

     

     

    SCSS에서 쉽게 관리하기

    /* mediaQuery.scss */
    $phone : 'only screen and (max-width : 768px)';
    $disktop : 'screen and (min-width: 769px)';
    @import './mediaQuery.scss';
    
    .body {
      @media #{$phone} {
         display : none;
      }
      
      @media #{$desktop} {
         display : block;
      }
    }

     

     

     

     

     

     

     

    반응형

    '• React' 카테고리의 다른 글

    [React] Ajax - axios  (0) 2021.10.25
    [React] useEffect / useReducer  (0) 2021.10.24
    [React] Router  (0) 2021.10.24
    [React] React hook basic  (0) 2021.10.21
    [REACT] State / Event  (0) 2021.09.04