DEV Community

James Hubert
James Hubert

Posted on

Project 94 of 100 - Random Color Generator 🎨

Hey! I'm on a mission to make 100 React.js projects. Please follow my dev.to profile or my twitter for updates and feel free to reach out if you have questions. Thanks for your support!

Link to the repo: github

Much like yesterday's project, today's is a simple, foundational project found at the beginning of many front-end oriented coding programs. That's because even though the app itself isn't super helpful (usually?) it does demonstrate our ability to handle state, and create some basic algorithms in our language of choice. It also demonstrates a firm handle of CSS, since you have to know how rgb values work.

First, we need to create the project with this command in the command line or Terminal:

expo init myAppName
Enter fullscreen mode Exit fullscreen mode

Today I'm working in a pure Javascript version of the React Native template so that's the option I chose. Next, you'll want to enter into the project folder and run npm start, then when it's clear the application is hosted on a local server in the command line, just press d to launch the Expo developer tools. When those are running in your browser, finally, press 'Run in web broswer' to launch the application there, or feel free to launch it in a local simulator, or scan the QR code to run it on your phone.

Next, open the project in your code editor and navigate to the App file. Mine is Javascript so it's called App.js. Feel free to clear out all of the code in the return() function except the outer View component. You can also get rid of the style prop on that, and remove the container property from the Stylesheet object below.

Let's start by adding a Button component to the template, inside your View. So make sure you're importing Button from the react-native package at the top of the file.

Now add a title prop to the button that says "Add new color" or something like that. For now, just leave the onPress prop blank.

We then need to pull in useState from our react import. Here's where we will keep track of the colors we display on screen by storing an array of colors in local state. Whenever we add a new color it will go in this array. Let's initialize it to an empty array.

const [colors, setColors] = useState([]);
Enter fullscreen mode Exit fullscreen mode

To build a function that generates a random color, one way is to know that any color property in CSS can take an rgb() value that accepts 3 integers as arguments from 0 to 256 which stand for red, green, and blue values respectively. Math.random() will generate a random number and Math.floor() will round down to the nearest integer. We can do this separately for each of the 3 values. Here's a function that creates a new shade in that range:

const generateShade = ()=> {
  return Math.floor( Math.random() * 256 );
}
Enter fullscreen mode Exit fullscreen mode

Now here's a function which calls this 3 times, once for each value in an rgb() color property and returns it:

const createNewColor = ()=> {
  const red = generateShade();
  const green = generateShade();
  const blue = generateShade();
  return `rgb( ${red}, ${green}, ${blue} )`;
}
Enter fullscreen mode Exit fullscreen mode

Next, we'll want to use the button to run createNewColor once each time it is pressed and store those values in state. Go back to the button you created earlier and in the onPress callback, call setColors() from state. Pass it a new array, with the previous values of colors destructured into it, as well as a call to createNewColor() as a new value in it, which returns a string with the rgb() format.

<Button
  title="Add new color"
  onPress={()=> setColors([...colors, createNewColor()])}
/>
Enter fullscreen mode Exit fullscreen mode

You can console.log() colors to the screen if you'd like to check how your state is changing now each time the button is pressed.

I also created another button beneath it that clears away all of the previous colors by passing an empty array to setColors() which looks like the following:

<Button
  title="Clear colors"
  onPress={()=> setColors([])}
/>
Enter fullscreen mode Exit fullscreen mode

Lastly, we just need to display those colors on the screen. For this we'll use a component. The data prop can take the colors value from state. The keyExtractor prop can use the item available to it from the component. renderItem should render an empty View component with a style prop set with a little height, a little width, and a backgroundColor property set to item, which will be a string representing a color value from our colors value in state.

<FlatList
  data={ colors }
  keyExtractor={item => item}
  renderItem={renderItem}
/>
Enter fullscreen mode Exit fullscreen mode

Here's a preview of what mine looks like after a few presses:

Image description

Not bad for a newbie, eh?

If you like projects like this and want to stay up to date with more, check out my Twitter @jwhubert91, I follow back! See you tomorrow for another project.

Top comments (0)