[TIL # 58] React Basic (3)

Yejin Yang·2022년 7월 29일
0

[TIL]

목록 보기
57/67
post-thumbnail

[수업 목표]

  1. React 컴포넌트에 스타일 적용하는 방법을 이해한다.
  2. React 로 간단한 TodoList 를 함께 만들어본다.

⭐️ 새롭게 안 사실

css module, styled components

해당 스타일이 해당 컴포넌트에서만 사용되게 스타일링 하는 방법!
Vue style의 scoped 태그와 유사한 느낌을 받았다.
styled components는 따로 설치가 필요하다.

  1. css module
  • *.module.css 파일을 만들고, import해서 사용한다
import React from 'react'
import style from '../styles/Button.module.css'

function Button() {
  return (
    <button className={style.Button}>
      <p>버튼</p>
    </button>
  )
}

export default Button
  • style이라는 이름으로 가져왔으면 style.클래스이름 의 형태로 className 에 지정을 해줘야 한다.
  • css module 의 경우 scss 와 같은 문법은 사용할 수 없고, 아래처럼 기본 css 문법을 사용해야한다.
  • 클래스를 한개 이상 부여하고 싶을 때: 템플릿리터럴 문법으로 적용
    <button className={`${style.Button} ${style.large}`}>

  1. styled components
    특정한 html 태그에다가 스타일을 이미 적용시킨 컴포넌트를 만들어놓는 방법
// 사용 법
import styled from 'styled-components'

const (변수명) = styled.(태그명)`

`
// 사용 예시 
import styled from 'styled-components'

export const Container = styled.div`
	width: 100px;
	background-color: blue;
`
  • components 폴더에 해당 컴포넌트 이름으로 폴더를 만들어서 그안에 index.jsx 와 style.js 파일 두개를 만들어 준다.
import React from 'react'
import * as S from './style'

function Button() {
  return (
    <S.Button>
      <p>버튼</p>
    </S.Button>
  )
}

export default Button
  • import * as S from './style' 로 가져오면, 앞서 작성한 스타일 파일 내부 변수들을 S 라는 이름으로 사용하겠다는 뜻이 되고 따라서 스타일 파일 내부 변수들을 S.(변수명) 형태로 사용할 수 있다.
  • style 파일에서 props 를 통해 특정 스타일 속성만 지정하도록 넘겨줄 수도 있다.
    background-color: ${(props) => props.color || 'blue'}; ->
    <S.Button color="#asdasd">
  • 비구조화 방법 :
    background-color: ${({ color }) => color || 'blue' }
  • 삼항연산자도 사용 가능!
    background-color: ${({ isClicked }) => (isClicked ? 'gray' : 'blue')};
  • 애니메이션: keyframes을 불러와서 사용
import styled, { keyframes } from 'styled-components'

const fadeIn = keyframes`
  from {
    opacity: 0
  }
  to {
    opacity: 1
  }
`

themeprovider

themeprovider 는 앱 전체에서 공통된 스타일 값을 쓸 수 있도록 도와주는 역할을 담당
팀 프로젝트할때 도입 하면 좋겠다고 생각했다.

styles 폴더 안에 theme.js 파일을 만들어서, 스타일을 지정한 뒤에
App.jsx에 themeprovider 로 감싸서, 앱 전체에 theme 에 정의한 스타일이 적용될 수 있도록 한다.

import { ThemeProvider } from 'styled-components'
import theme from './styles/theme'
import Button from './components/Button'

function App() {
  return (
    // hemeprovider 에 theme을 넘겨 준다.
    <ThemeProvider theme={theme}>
      <Button />
    </ThemeProvider>
  )
}

export default App
  • theme을 이용해서 props도 가능하다.
    background-color: ${({ theme }) => theme.palette.orange};

globalstyle 활용해서 폰트 추가하기

  1. 다운로드 받은 폰트를 assets>fonts 폴더 안 otf 파일을 넣어준다.
  2. theme.js 지정했던 styles폴더에 globalStyle.js 를 만들고 작성한다.
import { createGlobalStyle } from 'styled-components'
import NotoSansBold from '../assets/fonts/NotoSansKR-Bold.otf'

export default createGlobalStyle`
    @font-face {
        font-family: "NotoSansBold";
        src: url(${NotoSansBold}) format('opentype');
    }
`

format(’opentype’) 부분은 폰트 파일의 확장자에 따라서 변경해야한다.

otf → opentype
ttf → truetype
woff → woff

  1. App.jsx에 전역으로 불러와서 어디서든 쓸 수 있도록 셋팅
import { ThemeProvider } from 'styled-components'
import theme from './styles/theme'
import Button from './components/Button'
import GlobalStyle from './styles/globalStyle'

function App() {
  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />
      <Button />
    </ThemeProvider>
  )
}

export default App
  1. 적용하기: 사용할 컴포넌트 스타일에 font-family 를 설정

📌 꼭 기억할 것

상기 내용 전부!!!!

불변성 지키기

리액트 상태에서 객체를 수정할 때는 직접 수정하면 안된다!
리액트에서는 기존의 값을 가져온 뒤에 업데이트를 진행을 해야한다. 그래서 spread 문법(...)을 사용해서 기존 객체를 복사하여 새로운 객체를 만들고 이 새로운 객체에서 상태를 업데이트 해줘야 한다.

예제 코드

import React, {useState} from 'react'

function TodoAdd() {
  const [userInput, setUserInput] = useState({date: '', content: ''})

  const userInputHandler = (e) => {
    const {name, value} = e.target
    // name 키를 가진 값을 value 로 설정
    setUserInput({...userInput, [name]:value})
  }

  return (
    <div>
        <input type='date' name='date' onChange={userInputHandler}/>
        <input name='content' onChange={userInputHandler}/>
        <button>추가하기</button>
    </div>
  )
}

export default TodoAdd
  • userInput이라는 변수를 수정하고 싶을 때는 기존의 userInput이라는 값을 (...userInput) 불러온 뒤에 수정하고 싶은 내용을 넣어줘야 한다.
    [name]:value 로 상태를 업데이트 할 수있다.
    [name]과 대괄호를 사용하는 것은 변수로서 name이 들어올 수도 있고 nickname이 들어올 수 도 있다. 객체 키는 [name]: 'something' 이걸로 접근 및 값을 할당한다.
    객체에 값을 할당할때 동적인 키값으로 값을 할당할 때 대괄호로 감싸준다.

불변성을 지켜야 리액트가 컴포넌트의 상태가 업데이트 되었음을 감지할 수 있고 필요한 부분을 재렌더링 할 수 있다고 한다! 기존 상태를 직접 수정하는 경우 재랜더링이 되지 않는다.

꼭 기억하기 !

리액트에서 객체를 업데이트하게 될 때에는 기존 객체를 직접 수정하면 안되고, 새로운 객체를 만들어서, 새 객체에 변화를 주어야 됩니다.
https://react.vlpt.us/basic/09-multiple-inputs.html

profile
Frontend developer

0개의 댓글