In the previous lesson you found out what we’re going to build: a pixel coloring app!

Here we’ll create the first building block of the application. The smallest unit: a pixel.


Create a components folder in the src folder, and inside it create an empty Pixel.js file.

We’re going to import React, then we create a function component that simply outputs a div with two classes: pixel and the background property passed as a prop:

import React from 'react'

export default props => {
  return <div className={`${props.background} pixel`} />
}

I use an HTML class to determine the look of the component. Remember that React outputs any value found in the className attribute in JSX as the HTML class attribute. The name differs from “regular HTML” because class is a reserved word in JavaScript.

I style those classes using CSS, in src/styles.css, which is already existing, I define 4 colors, which I’ll use as the base for the app example:

.white {
  background-color: white;
}
.lightblue {
  background-color: rgb(0, 188, 212);
}
.blue {
  background-color: rgb(3, 169, 244);
}
.darkblue {
  background-color: rgb(33, 150, 243);
}

Where are these 4 colors defined? I define them in a Colors.js module, because they are used in various places.

export default ['white', 'lightblue', 'blue', 'darkblue']

The first color is the base color, and defines the color used by all cells when the app starts. The others are 3 choices I give to color the pixels.

Now let’s just add this one pixel in the app. Open src/index.js and after all the imports add

import Pixel from './components/Pixel'

and inside the App() function, make the component return one Pixel:

return (
  <div className="App">
    <Pixel />
  </div>
)

Let’s add a bit of styling to src/styles.css to make our Pixel actually appear on screen, by setting its width/height, and the border:

.pixel {
  width: 30px;
  height: 30px;
  border: 1px solid lightgray;
  box-sizing: border-box;
}

In your browser now you will see a little pixel showing up:

Wrapping up

In the next lesson we’ll combine this component and replicate it to create a grid of pixels.


Go to the next lesson