In the last few lessons we created a Canvas, composed by 900 pixels, and we made the pixels colorable using a background prop.

Now we’ll work on a ColorPicker component, which will allow us to choose between 4 different colors, and as such will be composed by 4 pixels.


Let’s create a new file in src/components named ColorPicker.js.

This will host our ColorPicker component.

The ColorPicker component as said in the introduction will simply host 4 instances of the Pixel component.

Everyone will have a different color. In the next lesson we’ll make it do something useful, but for now, we just need to display it correctly and add it to our app in the correct position.

So we start from zero:

import React from 'react'
import Pixel from './Pixel'

export default props => {
  return (
    <div className="colorpicker">
    </div>
  )
}

and we add 4 Pixel components by iterating over the Colors array, which is defined in the src/Colors.js file:

//...
import Colors from '../Colors'

export default props => {
  return (
    <div className="colorpicker">
      {Colors.map((color, index) => {
        return <Pixel key={index} background={color} />
      })}
    </div>
  )
}

We pass a background prop with a different color for each pixel, so we have 4 pixels, all colored differently. We can add new colors simply by adding a new entry in the src/Colors.js file.

Now we can import the ColorPicker component in the src/index.js file and render it in the template:

import React from 'react'
import ReactDOM from 'react-dom'

import './styles.css'
import Canvas from './components/Canvas'
import ColorPicker from './components/ColorPicker'

function App() {
  return (
    <div className="App">
      <ColorPicker />
      <Canvas />
    </div>
  )
}

const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)

Here it is in the browser preview:

Wrapping up

We wrapped 4 Pixel components in a ColorPicker component, assigning to each one of them a different color.

In the next lesson, we’ll change a property in the App component state when one of those pixels is clicked, to set the currently selected color.

See on CodeSandbox


Go to the next lesson