PROGRAMING/React

[REACT] Color picker

donghunl 2024. 3. 7. 03:41
반응형

Create a color-picking app so the user can select the page's background color.

 

Upon clicking a color, change the whole page's background to that color.

Make sure to use the Color subcomponent.

 

ColorPicker.js

import { useState } from 'react'
import Color from './Color'

const colors = [{
  hex: '#91A6FF',
  name: 'Cornflower Blue'
},
{
  hex: '#FF88DC',
  name: 'Persian Pink'
},
{
  hex: '#80FF72',
  name: 'Screamin Green'
},
{
  hex: '#FF5154',
  name: 'Tart Orange'
}]

export default function ColorPicker() {
  const [backgroundColor, setBackgroundColor] = useState('white')

  return (
    <div className='page' style={{ backgroundColor }}>
      {
        colors.map(color => (
          <Color key={color.hex} hex={color.hex} name={color.name} setBackgroundColor={setBackgroundColor} />
        ))
      }
    </div>
  )
}

 

Color.js

export default function Color({ hex, name, setBackgroundColor }) {
  return (
    <button
      className='color-square'
      style={{ backgroundColor: hex }}
      onClick={() => setBackgroundColor(hex)}
    >
      <h2>{name}</h2>
    </button>
  )
}

 

App.js

import ColorPicker from './ColorPicker'

function App () {
  return (
    <div className='App'>
      <ColorPicker />
    </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] Simple calculator - useReducer  (1) 2024.03.07
[REACT] Pixel art - React Context  (0) 2024.03.07
[REACT] Window event  (0) 2024.03.07
[REACT] Score Keeper - localStorage  (0) 2024.03.06
[REACT] Dog Picture - API  (0) 2024.03.06