In the previous lesson we introduced the ColorPicker component.
Now we put that component to good use. When the user clicks the button we’ll change the default color of the application. This will be in turn used in the next lesson when we’ll allow to color pixels by clicking with the mouse.
The user must be able to click one of the colors in the color picker, and select it to draw something.
First, let’s make the default color highlighted when the app starts.
In src/index.js
we store the current color in the color
property of the state:
import React, { useState } from 'react'
//... in App()
const [color, setColor] = useState(0)
Let’s pass it down to the ColorPicker
component:
<ColorPicker currentColor={color} />
Now inside the ColorPicker
component, we use this prop to identify the current color:
<Pixel
key={index}
background={color}
current={Colors[props.currentColor] === color}
/>
Every pixel now will get a current
prop that’s either true
or false
.
If it’s true, we’re going to add a current-color
class to the Pixel component, in src/components/Pixel.js
:
export default props => {
return (
<div
className={`${props.background} pixel ${
props.current ? 'current-color' : ''
}`}
/>
)
}
which we style in src/styles.css
to make it highlighted, have a bigger border:
.pixel.current-color {
border: 4px solid yellow;
}
Cool! Now we need to let the user change this color.
When the Pixel component in the ColorPicker is clicked, we must update the currently selected color. We start by adding an onClick
property to the Pixel JSX:
export default props => {
return (
<div
className={`${props.background} pixel ${
props.current ? 'current-color' : ''
}`}
onClick={props.onClick}
/>
)
}
which calls a function that’s passed down by the parent component, ColorPicker
:
<Pixel
onClick={e => props.setColor(index)}
key={index}
background={color}
current={Colors[props.currentColor] === color}
/>
See, we pass an arrow function to onClick
which calls the props.setColor()
function, which is passed by the App
component.
In App.js we add setColor()
and we pass it to ColorPicker
as a prop:
function App() {
const [color, setColor] = useState(0)
return (
<div className="App">
<ColorPicker currentColor={color}
setColor={color => setColor(color)} />
<Canvas />
</div>
)
}
We can now choose another color from the list, and that will be the new default!
Wrapping up
In this lesson, probably the most complex of this module, you first added a centralized place to store the current color in the App component.
Then you set up an event system to handle changing the color when a Pixel in the ColorPicker is clicked.
Let’s go to the next lesson to start coloring the pixels in the canvas!