React

React에서 CSS 작업

정중식 2019. 11. 9. 15:42

짚고 넘어가기..

  • 리액트를 사용하는 가장 핵심은 어플리케이션 캡슐화다.
  • 한 컴포넌트에 html, javascript, css등을 다 가지는..

리액트에서 CSS 작업 방법

  • create-react-app 덕분에 Header.module.css 이런식의 css파일 이름 설정이 가능
  • 전역으로 className을 사용하는게 아닌, 로컬로 사용하게끔 설정해준것임
    (한 파일에 한css라고 생각)
  • Header.css => Header.module.css
  • import "./Header"; => import styles from "./Header.module.css"; css Import 형식에서 js Import 형식으로 전환
  • 임의로 클래스이름이 정해짐
  • jsx에서 사용예시: <ul className={styles.navList}>
import React from "react";
import styles from "./Header.module.css";

export default () => (
  <header>
    <ul className={styles.navList}>
      <li>
        <a href="/">Movies</a>
      </li>
      <li>
        <a href="/tv">TV</a>
      </li>
      <li>
        <a href="/search">Search</a>
      </li>
    </ul>
  </header>
);
.navList {
  display: flex;
}

.navList:hover {
  background-color: blue;
}

단점

  • 작은 프로젝트에서는 좋으나 큰 프로젝트에서는 샤용할때 클래스이름을 기억해야한다는 번거로움이 있음
  • css에서 .nav-list {} 이런식으로 하면 작동하지않음
  • js에서 사용예시
    <ul className={styles.nav-List}> => X
    <ul className={styles.["nav-list"]}> => O

리액트에서 CSS 작업 방법 scss

  • node-sass install
.navList {
  display: flex;
  &:hover {
    background-color: blue;
  }
}
import styles from "./Header.module.scss";
  • Header.module.css => Header.module.scss 로 파일 이름변경

javascript를 이용한 CSS

  • 이 방법이 가장 깔끔함
  • styles-components
    • yarn add styles-components
    • style이 안에있는 컴포넌트를 생성할 수 있게됨
  • 마찬가지로 임의로 클래스이름이 정해짐

import React from "react";
import styled from "styled-components";

const Header = styled.header``;

const List = styled.ul`
  display: flex;
  &:hover {
    background-color: blue;
  }
`;

const Item = styled.li``;

export default () => (
  <Header>
    <List>
      <Item>
        <a href="/">Movies</a>
      </Item>
      <Item>
        <a href="/tv">TV</a>
      </Item>
      <Item>
        <a href="/search">Search</a>
      </Item>
    </List>
  </Header>
);
  • `` 백틱안에 css설정
  • 컴포넌트에 스타일 변수 적어주면됨

react-router-dom의 Link 사용

  • Link는 해당 페이지가 내 어플리케이션에 있으면, 브라우저의 방식이아닌 Javascript의 방식으로 이동시켜줌
  • 앱을 새로고침하는게아닌 리액트의 상태만을 고쳐주기때문에 a 링크 사용보다 빠름
  • import { Link } from "react-router-dom";
    • React Router에서 주어진 Link사용
  • href => to

import React from "react";
import { Link } from "react-router-dom";
import styled from "styled-components";

const Header = styled.header``;

const List = styled.ul`
  display: flex;
  &:hover {
    background-color: blue;
  }
`;

const Item = styled.li``;

const SLink = styled(Link)``;

export default () => (
  <Header>
    <List>
      <Item>
        <SLink to="/">Movies</SLink>
      </Item>
      <Item>
        <SLink to="/tv">TV</SLink>
      </Item>
      <Item>
        <SLink to="/search">Search</SLink>
      </Item>
    </List>
  </Header>
);