DEV Community

oladejo abdullahi
oladejo abdullahi

Posted on • Edited on

Hexadecimal Code Generator using React(Beginner)

Table of Contents

Introduction

One of the problem developer encounter while developing a website is how to get colors that suit our design. well, you probably could have learn many color names however most of the time the you may still not get the preferable color, that is why hexadecimal exist. Hexadecimal color code gives you thousands of color but it will be hard to be certain of how each color code will look like. Hence, it will be nice if we can build a app that will generate us random codes with result. Here we can easily pick the color will like.

Getting Started

To get Started You should have good knowledge of the following

  1. HTML
  2. CSS
  3. JavaScript
  4. React() Just like listed above you don't have to know much about React before you could able to do this app.

Setting up the Environment

Before writing any code you need to install react and node Js. I believed you should already have that as a learner of React. So Here I will be using node to run our app.
if you don't have it install kindly click on this link to download and install it.

Creating React App

Now that the node has been in stall let us set up a React Environment on our computer so that we can learn and test React.

To create a react app we will be using create-react-app command.

What is create-react-app?
The create-react-app is an officially supported way to create React applications.
If you have NPM and Node.js installed, you can create a React application by first installing the create-react-app. let's see how to do that with command.

Install create-react-app by running the following command in your terminal:



C:\Users\Your Name>npm install -g create-react-app


Enter fullscreen mode Exit fullscreen mode

You are now ready to create your first React application!

Run the following command to create a React application named HexadecimalCode:



C:\Users\Your Name>npx create-react-app HexadeciimalCode


Enter fullscreen mode Exit fullscreen mode

Explanation on the command
The create-react-app will set up everything you need to run a React application.
the second command (npx create-react-app projectName) create React application that you want to work on. Note: HexadecimalCode could be exchange with any name. we used HexadecimalCode here because that is the name of our app. so feel free to use any project name
Note: This tutorial uses create-react-app to demonstrate React examples. You will not be able to run the same examples on your computer if you do not install the create-react-app environment.

Running the React Application

If you followed the two commands above, you are ready to run your Hexadecimal React application!

Run the following command to move to the Hexadecimal directory and excute the app:



C:\Users\Your Name>cd myfirstreact
C:\Users\Your Name\myfirstreact>npm start


Enter fullscreen mode Exit fullscreen mode

A new browser window will pop up with your newly created React App! If not, open your browser and type localhost:3000 in the address bar.
Now we can start writing the codes.

Writing React directly to HTML file

Many students often asked me 'Is there no way to write react without using this node and setting up all this and that environment that is data and time consuming?'
my answer is 'of course there is.'. yeah there is a way to write it without setting up or installing all this necessary thing all you just have to do is to connect with WiFi any time you want to run such a file.

The quickest way start learning React is to write React directly in your HTML files.
Start by including three scripts, the first two let you write React code in your JavaScripts, and the third, Babel, allows you to write JSX syntax and ES6 in older browsers.

Example

open an html file and type the following code to see.



<!DOCTYPE html>
<html>
  <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
  <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
  <body>

    <div id="mydiv"></div>

    <script type="text/babel">
      class Hello extends React.Component {
        render() {
          return <h1>Hello World!</h1>
        }
      }

      ReactDOM.render(<Hello />, document.getElementById('mydiv'))
    </script>
  </body>
</html>



Enter fullscreen mode Exit fullscreen mode

Result>>

Image description
as you can see above the first three script replaced the necessary thing to be installed. now you can choose which ever one you want to use for this app.

Writing Codes For Hexadecimal App

Our App will be made up of three components listed below

  1. Header
  2. Hexadecimal Codes
  3. Button

Creating Header Component

Header: this contains the header of the page we can write little description of our app here I believed this is not the first time you have heard this.
So let's write the codes for that now.

Now Open your index.js that is inside src directory delete everything there and start typing the following codes step by step.

Step1: import the necessary things.
src/index.js



import React from 'react'
import React-DOM from 'react-dom'


Enter fullscreen mode Exit fullscreen mode

we just import react library into our script now let's tart writing our own codes.
Step2: create Header Component
add the following codes in index.js to create Header component

Header Component>>



/*creating the header components and styling it.*/
const Header=function(props){
  const headerStyle={
              color:'white',
              padding:'5px 0px 3px 18px',
              margin:'0px'}

  return (
  <div style={headerStyle}>
    <h2 style={{textAlign:'center'}}>30Days Of React Project</h2>
    <h3>{props.title}</h3>
      {props.info}
  </div>
  )
}



Enter fullscreen mode Exit fullscreen mode
Explanation

The above codes create functional Header Component. If you study the codes it is very similar to creating function in javascript where props is the fuction argument or parameters.
headerStyle: this is a variabel that holds the style we wish to give the header component. this is just like writing CSS in html only that you have to put each value assigned to properties in string format. Also some properties like
font-size,padding-left,max-width etc have to be written in camelCase i.e fontSize,paddingLeft,maxWidth etc.
inside the Function we returned the JSX element, add style to the div element. we also add style to h2 element. the style in h2 element here is inline hence we need to write the bracket two times.
Note: variable are called in JSX codes by writing it in bracket. this was used for headerStyle, props.title and props.info.
Looking at the way we used props in should have known that props will be an object that has info and title as its properties.
Note: props should be used all the time and your component name should be written in capital letter. if you are using CDN link all your codes must be written inside the last script tags.

Executing the Header Component.

Don't be surprise that the codes changes nothing on browser, that is because we have never called the component remember the component is just a function. we need to call a function before it can be executed. Now execute it by adding the following codes.

Header Execution Code>>



const headerInfo=(<p>The following shows different Hexadecimal 
    codes and their respective color result.
    copy the best color codes for your web. <br/>
    <b>Note:</b> it generate different codes on reload</p>)

const headerTitle='Day1: Hexadecimal color Generator'

 ReactDOM.render(<Header title={headerTitle} info={headerInfo}/>
, document.getElementById('root'));


Enter fullscreen mode Exit fullscreen mode

Explanation:
In the codes above we create two variables headerInfo and headerTitle they hold the info and title of the header part.if you like you can write anything you like there.
We also executed the component by using ReactDOM.render() function, the function take two parameter

  1. Component: the component we want to execute which is Header
  2. DOM root: this is where to dump the whole component. a 'div' has been created in index.html that has the id. so we are referring to it.

Result>>

Image description
Now reload the browser and see what you have gotten. Did you see what we have??
Try to re-edit it if you would like to add more content to it.
For now the picture below shows what we just did.

Now let's add the style needed for body.
Navigate to the current working directory. go back to the parent folder and select public. inside public folder you will see index.html. add the following codes to it.

public/index.html



 body{background: #00afff;
     border:7px solid #33af;
     margin:0;
   }    


Enter fullscreen mode Exit fullscreen mode

after adding it your page should look like below

Result>>
Image description

Creating the ColorGenerator Component

Here we are going to create Color generator Component. But we need to understand the nature of what we want to do. The task is to generate different color codes and display their color in each box this means we will need to create many 'div' element of each div contain one color-code and the background of the div is equivaent to the code. Hence we will divide this compoment into three segment

  1. Div Component: this component hold an hexadecimal color code and has the background to be that hexadecimal codes. Note: this is generated at random.

Creating Div Component.

Type the following codes to create Div component that hold just a color code.
Note: delete the last line codes of index.js before you type the following codes



/*creating the color Div functional components and styling it.*/
const Div=()=>{
/*generating the Hexadecimal color codes using array*/
const digit='1234567890abcdef'
 const colorCode=[1,2,3,4,5,6].reduce((prev,curr)=>
prev+=digit[Math.floor(Math.random()*digit.length)],'#')
/*creating a style of the div that will has the color codes generated as background*/
const divStyle={background:colorCode,
        border:'white solid 2px',
        color:'white',
        margin:'1px',
        maxWidth:'90px',
        display:'inline-block',
        textAlign:'center'}

/*creating the div element that has background and text to be the color codes*/
return (<div style={divStyle} className='container'>
            <h2 style={{fontSize:'18px'}}>{colorCode}</h2>
          </div>)
}



Enter fullscreen mode Exit fullscreen mode

Explanation
The codes above is going to generate random color-code and make it as the background of div create while the colorCode is also written as text in h2 tags.
Now let let's create a component that will generate N-numbers of that by looping it.

Creating Alldiv Component



/*creating the functional components that create as many div color as we wish and styling it.*/

const Alldiv=({number})=>{
  let divList=Array(number).fill(0)
    const allDivElement=divList.map((div,key)=><Div key={key}/>)
    return (<div>
             <h3>Hexadecimal Codes</h3>
            {allDivElement}
         </div>)
}


Enter fullscreen mode Exit fullscreen mode

Explanation
The codes above Create a component that takes number as parameter, it should be noted that the number is written in a bracket. in this kind of case we are not using props hence number is treated like a variable. We created divList this contains array of zeroes. we loop through this using list method map() function and return div element with random color-code as text and background. Recall we already created a component name Div before.
Note: whenever you are creating many elements of the same kind like that it is important to provide key. each key have to be a unique one so that React will not see it as duplicating the same element.
Note: the way we created the component is not differ from the previous except that we used arrow function here. you could have do the same thing for others too if you don't like typing function all the time.

Executing AllDiv Component.

Now just like we did for Header the other time let us execute Alldiv Component to see if it works well, For now the Header is not going to work. Your whole codes should like below.



import React from 'react'
import ReactDOM from 'react-dom'
/*creating the header components and styling it.*/
const Header=function(props){
  const headerStyle={
        color:'white',
        padding:'5px 0px 3px 18px',
        margin:'0px'}

  return (
  <div style={headerStyle}>
    <h2 style={{textAlign:'center',background:'#5454aa'}}>30Days Of React Project</h2>
    <h3>{props.title}</h3>
      {props.info}
  </div>
  )
}


const headerInfo=(<p>The following shows different Hexadecimal 
    codes and their respective color result.
    copy the best color codes for your web. <br/>
    <b>Note:</b> it generate different codes on reload</p>)

const headerTitle='Day1: Hexadecimal color Generator'


/*creating the color Div functional components and styling it.*/
const Div=()=>{
/*generating the Hexadecimal color codes using array*/
const digit='1234567890abcdef'
const colorCode=[1,2,3,4,5,6].reduce((prev,curr)=>
prev+=digit[Math.floor(Math.random()*digit.length)],'#')

/*creating a style of the div that will has the color codes generated as background*/
const divStyle={background:colorCode,
        border:'white solid 2px',
        color:'white',
        margin:'1px',
        maxWidth:'90px',
        display:'inline-block',
        textAlign:'center'}

/*creating the div element that has background and text to be the color codes*/
return (<div style={divStyle} className='container'>
            <h2 style={{fontSize:'18px'}}>{colorCode}</h2>
          </div>)
}


/*creating the functional components that create as many div color as we wish and styling it.*/

const Alldiv=({number})=>{
  let divList=Array(number).fill(0)
    const allDivElement=divList.map((div,key)=><Div key={key}/>)
    return (<div>
             <h3>Hexadecimal Codes</h3>
            {allDivElement}
         </div>)
}
ReactDOM.render(<AllDiv number={100}/>, document.getElementById('root'));


Enter fullscreen mode Exit fullscreen mode

Result>>

Image description

As you can see above we only render All div Component and not Header anymore. But we need both Header and Alldiv to be render on our page. so how do we do that?? it is very easy we just need to create another component that will return both while both of them will be in a parent element div. so delete the last line of previous code add the following codes.




const Hexadecimal=()=>(<div>
                        <Header title={headerTitle} info={headerInfo}/>
                        <Alldiv number={200}/>
                      </div>)
ReactDOM.render(<Hexadecimal/>, document.getElementById('root'));


Enter fullscreen mode Exit fullscreen mode

Result>>

Image description
In the above codes we marge Header and AllDiv components to create Hexadecimal Component. then we render Hexadecimal component using render method.

Creating Button Component

Now we are almost done with our app. For now anytime you reload the browser you get different random color codes. but How about creating a button that will be generating new random one instead of reloading the page?? That will be cool right?? Alright let's create a Button Component that will do that By editing the Hexadecimal component codes.

Codes




const Button=(props)=>{ 
         const buttonStyle={
            background:'#0588b0' ,
            color:'white',
            padding:'11px',
            pointer:'corsor',
            margin:'9px',
            borderRadius:'14px',
            border:'solid 3px #8ec0ff'}
         return (<div style={{textAlign:'center'}}>
                     <button style={buttonStyle}
                             onClick={()=>document.location.reload()}>
                       Generate New Colors</button>
                 </div>)

       }


const Hexadecimal=()=>(<div style={{borderRadius:'15px',margin:'10px'}}>
                        <Header title={headerTitle} info={headerInfo}/>
                        <Alldiv number={200}/>
                        <Button/>
                      </div>)

ReactDOM.render(<AllDiv number={100}/>, document.getElementById('root'));


Enter fullscreen mode Exit fullscreen mode

Result>>

Image description
in the codes above we created Button Component with its style written in it. we also add clicking event to it such that the document will reload whenever the button has been clicked.
We also add Button component to our Hexadecimal component so that it comprises of three components.

Wooow! we are done with the App. The following show the whole codes and the result.

Codes>>



import React from 'react'
import ReactDOM from 'react-dom'
/*creating the header components and styling it.*/
const Header=function(props){
  const headerStyle={
        background:'#0588b0',
        color:'white',
        padding:'5px 0px 3px 18px',
        margin:'0px'}

  return (
  <div style={headerStyle}>
    <h2 style={{textAlign:'center',
                }}>
      30Days Of React Project</h2>
    <h3>{props.title}</h3>
      {props.info}
  </div>
  )
}


const headerInfo=(<p>The following shows different Hexadecimal 
    codes and their respective color result.
    copy the best color codes for your web. <br/>
    <b>Note:</b> it generate different codes on reload</p>)

const headerTitle='Day1: Hexadecimal color Generator'


/*creating the color Div functional components and styling it.*/
const Div=()=>{
/*generating the Hexadecimal color codes using array*/
const digit='1234567890abcdef'
const colorCode=[1,2,3,4,5,6].reduce((prev,curr)=>
prev+=digit[Math.floor(Math.random()*digit.length)],'#')

/*creating a style of the div that will has the color codes generated as background*/
const divStyle={background:colorCode,
        border:'white solid 2px',
        color:'white',
        margin:'1px',
        maxWidth:'90px',
        display:'inline-block',
        textAlign:'center'}

/*creating the div element that has background and text to be the color codes*/
return (<div style={divStyle} className='container'>
            <h2 style={{fontSize:'18px'}}>{colorCode}</h2>
          </div>)
}


/*creating the functional components that create as many div color as we wish and styling it.*/

const Alldiv=({number})=>{
  let divList=Array(number).fill(0)
    const allDivElement=divList.map((div,key)=><Div key={key}/>)
    return (<div style={{textAlign:'center',
                         background:'white'}}>
             <h3>Hexadecimal Codes</h3>
            {allDivElement}
         </div>)
}


/* Creating Button component it is going to generate button*/
const Button=(props)=>{ 
         const buttonStyle={
            background:'#0588b0' ,
            color:'white',
            padding:'11px',
            pointer:'corsor',
            margin:'9px',
            borderRadius:'14px',
            border:'solid 3px #8ec0ff'}
         return (<div style={{textAlign:'center'}}>
                     <button style={buttonStyle}
                             onClick={()=>document.location.reload()}>
                       Generate New Colors</button>
                 </div>)

       }


/*creating the Hexadecimal component that marge all the necessary components*/
const Hexadecimal=()=>(<div style={{borderRadius:'15px',margin:'10px'}}>
                        <Header title={headerTitle} info={headerInfo}/>
                        <Alldiv number={200}/>
                        <Button/>
                      </div>)

ReactDOM.render(<Hexadecimal/>, document.getElementById('root'));


Enter fullscreen mode Exit fullscreen mode

I hope you learn something from this article?? if you have any question or correction feel free to chat me up on whatsapp, or mail me. You can also connect with me on twitter or linkedIn.

Top comments (0)