Fall in IT.

[React] Context API 알아보기 본문

프레임워크/React

[React] Context API 알아보기

D.Y 2021. 4. 5. 22:14

Context API란?

  • Context API는 리액트 프로젝트에서 전역적으로 사용할 데이터가 있을때 유용한 기술이다
  • 예를 들면, 사용자 로그인 정보, 애플리케이션 환경 설정, 테마 등

 

 

Context API 사용법 익히기

 

color.tsx - Context API 만들기

const ColorContext = createContext({
  state: { color: 'black', subColor: 'tomato' },
  actions: {
    setColor: (color: string) => {},
	setSubColor: (color: string) => {},
  }
})

export default ColorContext


interface ColorProviderIProps {
  children: React.ReactNode
}

function ColorProvider({ children }: ColorProviderIProps): JSX.Element {
  const [color, setColor] = useState('black')
  const [subColor, setSubColor] = useState('tomato')

  const value: any = {
	state: { color, subColor },
	actions: { setColor, setSubColor }
  } 

  return <ColorContext.Provider value={value}>{children}</ColorContext.Provider>
}

export { ColorProvider }

 

App.tsx - Context 사용하기

import React from 'react'
import './App.css'
import ColorBox from './components/ColorBox'
import SelectColors from './components/SelectColor'
import { ColorProvider } from './contexts/color'

function App() {
  return (
    <ColorProvider>
      <div className="App">
        <SelectColors />
        <ColorBox />
      </div>
    </ColorProvider>
  )
}

export default App

 

ColorBox.tsx

import React, { useContext } from 'react'
import ColorContext from '../contexts/color'

function ColorBox(): JSX.Element {
  const { state } = useContext(ColorContext)

  return (
    <>
      <div
        style={{
          width: '64px',
          height: '64px',
          background: state.color,
        }}
      />
      <div
        style={{
          width: '32px',
          height: '32px',
          background: state.subColor,
        }}
      />
    </>
  )
}

export default ColorBox

 

SelectColor.tsx

import React, { useContext } from 'react'
import ColorContext from '../contexts/color'

const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']

function SelectColors() {
  const { actions } = useContext(ColorContext)

  return (
    <div>
      <h2>색상을 선택하세요.</h2>
      <div style={{ display: 'flex' }}>
        {colors.map((color) => (
          <div
            key={color}
            style={{
              background: color,
              width: '48px',
              height: '48px',
              cursor: 'pointer',
            }}
            onClick={() => actions.setColor(color)}
            onContextMenu={(event) => {
              event.preventDefault()
              actions.setSubColor(color)
            }}
          />
        ))}
      </div>
      <hr />
    </div>
  )
}

export default SelectColors

 

참조  

 

Comments