PROGRAMING/React

[REACT] Pixel art - React Context

donghunl 2024. 3. 7. 04:34
반응형

Build a pixel art drawing app.

React Context: Allows you to share data between components more easily. Instead of having to pass a prop down multiple levels, you can use Context.

 

When a color is clicked, that color becomes the drawing color, Then, when one of the grid squares is clicked, it should be colored in with the drawing color.

Use React Context to share the state between your components.

 

PixelArt.js

import { createContext, useContext, useState } from 'react'

const ColorContext = createContext({
  color: 'lightGrey',
  setColor: () => {}
})

function ColorPicker () {
  const { setColor } = useContext(ColorContext)

  const colors = ['red', 'blue', 'yellow', 'green', 'black', 'white', 'purple']
  return (
    <div>
      <h1>Choose a color</h1>
      {colors.map(color => (
        <button
          key={color}
          style={{ backgroundColor: color }}
          onClick={() => setColor(color)}
        />))}
    </div>
  )
}

function Pixel () {
  const { color } = useContext(ColorContext)
  const [pixelColor, setPixelColor] = useState('lightGrey')

  return <button onClick={() => setPixelColor(color)} style={{ height: '20px', width: '20px', backgroundColor: pixelColor, margin: '1px' }} />
}

function Pixels () {
  const pixels = []
  for (let i = 0; i < 100; i++) pixels.push(<Pixel key={i} />)
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(10, 1fr)', width: '210px', margin: '0 auto' }}>
      {pixels}
    </div>
  )
}

export default function PixelArt () {
  const [color, setColor] = useState('lightGrey')

  return (
    <ColorContext.Provider value={{ color, setColor }}>
      <ColorPicker />
      <Pixels />
    </ColorContext.Provider>
  )
}

 

App.js

import PixelArt from './PixelArt'

function App () {
  return (
    <div className='App'>
      <PixelArt />
    </div>
  )
}

export default App

 

index.js

import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import reportWebVitals from './reportWebVitals'

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
)

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals()

 

결과 화면

반응형

'PROGRAMING > React' 카테고리의 다른 글

[REACT] Focus an input - useRef  (1) 2024.03.07
[REACT] Simple calculator - useReducer  (1) 2024.03.07
[REACT] Color picker  (0) 2024.03.07
[REACT] Window event  (0) 2024.03.07
[REACT] Score Keeper - localStorage  (0) 2024.03.06