Simple Painter in ReactJS — useContext, useState

A simple painter, where you pick a color from a set of preselected ones. And then paint a grid cell with that color. We will be using React Hooks, more specifically useContext and useState. Context will give our components a context of color, which can be set via useState hook.

Photo by Eddy Klaus on Unsplash


Create a react app, with create-react-app. I’m using the 3.0.0 version. For design layout I’ll use the Bulma CSS. It’s very easy to use.

First, create components and contexts folders. These will contains, as the name already tells us components and contexts.

Index.js should look like this now:


Starting with a context. Now this context will just be empty at the beginning, but it’s nice to have contexts into their own folders.


App is our main component. It contains all the components we will use. Think of it as a layout component. In it we use the first of React Hooks — useState. This will give us a variable color and a setter to change it.

Now when we defined the Context.Provider we can set what values it will have. In our case we want that the context contains a list of colors, the current selected color and the setter to change it.

This component uses contexts colors and the setter to set the selected color. It just displays a list of all available colors to pick. Once we click on the color, the color is passed to setColor.

This component is pretty simple. From context it takes the current selected color and that info it displays to the user.

This one may be a little long. From context we take the colors and the current color. Then we need to draw a grid, the grid is a 2D array.. This grid will be of size 10x10. For storing what color is on what point on the grid we use useState.

When we do actually draw the table representing the grid. We must handle the click and mousemove events of the cell. Nobody wants to click 100 times, you want to just drag across the grid. But when we drag, the left mouse button must be pressed, otherwise it will just rewrite the cell all the time.

Also to save us from unnecessary re-draws, we have to check is the color of a given cell is already that color. If it is, then there is no need to update the grid, as it will make no difference.


Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store