Featured Post

BUILD A TODO LIST IN PYTHON

Image
Build a TODO List in Python Overview The objective is to build a todo list to which we can add items, remove the added items, edit the items and even if required, delete out the entire list itself. We will learn here step by step, how to build the todo list with the above  CRUD (Create, Remove, Update/edit, and Delete ) features.  This is a CRUD list  app  that we are building as we can Create, Remove, Update items in the list and Delete the entire list itself. We will be using Python3 to build this Project. Importing os and time We import time to let the screen pause for a while before clearing  and we import os to clear the screen . Initializing the list We initialize the todo list with an empty list as there are not items added yet to the list and this is represented in the code aby using an empty square braces   toDoList = [] Defining the print list  The def keyword is used to define a function in python. In the below code, we define the function called printList(). When we define

Build A Random Quote Machine in React

 Build A Random Quote Machine in React 

This ReactJS Tutorial will teach you how to create a random quote generator using React hooks. This is a challenge for testing your frontend libraries in the freeCodeCamp frontend libraries certification projects and in this challenge, I will walk you through the steps so that you can pass all the ten tests in this challenge.



This React Project is part of the freeCodeCamp frontend Libraries Certification Challenges and here, I am going to walk you through the challenge and also break down the challenge into smaller, more understandable steps, to demonstrate how to build this App in a simple way.

The Random Quote Machine App is a very unique app that will allow the users to interact with the app , whereby by clicking on a button, you will be able to see random new quotes with their authors' names and you will also be able to share these quotes on Twitter. 

Code editors required for this challenge : 

We will be coding in HTML, CSS and JavaScript files. For this project, I have coded on two cloud editors, namely, CodePen and also Jsitor. You could sign up for  a CodePen account if you don't have one  or you could also sign up for a Jsitor account. 

Before we start coding a project , it is essential to understand the project in a no-code or pseudocode way, that is, make a reality check and rough layout of the project and consider what it would like as a finished product and what are the main ingredients that are part of the output in order to tackle the whole process smoothly without any hickups.

The Pseudocode for understanding the project challenge:

We consider the layout of the App that we are going to build, that is, the Random Quote Machine , with the help of the diagram above. In the above picture, I have taken a screenshot of the actual image of the app output) , we notice the following :

There is a main container with another box inside this container and this box termed, the QuoteBox container with a blue background in the main container. The QuoteBox has following :

There are some lines of quotes and below the quote, we see the author's name.

There is a button called 'New Quote' button and another button beside it called the 'Tweet' button. 

The QuoteBox container with the above items also has a colored background. Current color of the QuoteBox background is black, but, it is supposed to keep changing colors every time the quote keeps changing or rather every time, a new random quote appears on the screen when the user clicks on the New Quote button. The purpose of the Tweet button beside the New Quote button, is to share the new quotes that appears here, on the Twitter landing page.

Code for the HTML file:

In the HTML file, we write the below code. This means the main component is the App Component and the rest of the components and elements we will be building inside this main app. The app has a container with a div id of "app". Hence, this explains the code entered below.

The code in HTML  file:

  
   <div id="app"></div>



In the JavaScript file, I am going to break down the code into smaller bits to explain each code below.

Creating the quoteData Object to store quotes data:

We create an Object and let's give it a name of  quoteData.  This Object has two properties, a text property and author property. In other words, the object quoteData has two items , namely, the quote text and the respective author's names. You have already learnt about JavaScript Objects earlier and if not, I will be also coming up with a a post for this topic soon.  An Object is something  that has  properties that makes it specific to the Object. For example, the object car would have four tyres, a driving gear, few seats and some doors etc. So, this quoteData object will store the data of all the quotes and their respective author names in order for them to be retrieved later when the user interacts with the App.

Now that you have some idea on what an object is , let me go on to explain how you could get access to these quote texts with their respective authors' names for this quotaData object. You could look up google for different types of sayings or quotes - there are so many available online! Then, you can copy and paste those quotes' text with their authors' names in this quoteData here. Please note here that an Object is enclosed within a pair of square braces and the quote text as well as the author names are enclosed within curly braces as they are string items. You may include any number of items in this data , say 100 quotes or even more or less, it is up to you what is your style of creativity when you create this interesting  quoteData. So, now, we have an object quoteData to store all the data related to the text of the quotes and their author names.
Now, you may wonder how to get hold of so many quotes for storing in this object? You can google for quotes and copy the quotes in this object, unless, you are great with creating your own quotes!
Here, we are not testing your ability to write quotes, but, rather, we are testing your skill on gathering the required data to proceed for your project.

Create an array backgroundColors to store background colors:
Next, we create an array to store all the background colors - we want to have different background colors appear behind the different quotes, meaning, whenever the quotes changes in the app, their background colors will also change. This is to add a level of interesting user experience ! Ideally, if there are 100 quotes stored in the quoteData, then, you should store 100 background colors in the array where you are storing the colors. Let us call this array ,  backgroundColors, that helps to store all the different background colors for appearing in the background of the various quotes that we are storing.

Create QuoteBox Component:
The next step would involve create a Component to house within the main App. Let us call this Component, QuoteBox. We do this by declaring a constant QuoteBox with a function that takes two parameters : quote and handleNewQuote.

The handleNewQuote is an onClick event handler that helps the users to interact with the App, when an event is fired. In this case. when the user clicks on the New quote button, the app is able to generate a new random quote with a random index.
Now, let's see  what all are stored inside this QuoteBox  Component: It needs to store the quote text and author name, a button which when clicked generates new quotes and a button which when clicked shares this generated quote on twitter.

The QuoteBox container has a div id of "quote-box" , that contains a paragraph element p with an id of "text" that will execute the quote text by writing quote.text within curly braces, since curly braces will help to implement the JavaScript code. Next, we need to mention the author name under the quote text. Hence, write the h2 with an id of "author" and write {quote.author} within curly braces, to execute the author name below the the respective quote.

As you already know, in React, writing the JavaScript in curly braces will instruct the React Component to treat it as a JavaScript code in order to execute the specific task as a JavaScript.

Inside the QuoteBox container. we also need to create two buttons, one button to generate new quotes along with respective author's  name on clicking it and another one to share this quote by tweeting it.
Let's call the button generating new quotes as New Quote, and this button has a div class of "click" and button class of "btn". This button has an onClick property with a value of {handleNewQuote}, mentioned within curly braces to let the app execute this JavaScript code. Running this code will trigger the generation of new quote upon clicking the New Quote button. This will trigger the generation of new quote every time a user interacts with the App by clicking on the New quote button.
Next to the New Quote  button, we need to make a button to tweet these quotes.  Let's  call it  the Tweet button , right next to the New Quote button, in order to tweet the quote generated, the anchor tag has a hyper link with an id of "tweet-quote" , and the function of this Tweet button is to take the user to a Twitter landing page, upon clicking the this button.

Create the getRandomIndex function:

The next step would be to make a function to calculate the maximum number of  instances of the random quotes. Make an arrow function with constant getRandomIndex using math.random method, by multiplying the Math.random  by the total length of the quotaData and with this result, the math.floor method is performed  to round off the integers to whole numbers.


Create the App Component:

Let's create the App Component which is the main component of the App that we are building for this project. The variable constant app is assigned a function  which are having two parameters,  quote and setQuote.

The setQuote will update the quote in the app component.  The useState  hook will allow us to track the state in this component and shows us the current value of the quote when we interact with the App.  So, this explains the usage of useState and setState hooks in React App. 

Next, we create a handleNewQuote function and using the setState hook, that is in this case, the setQuote hook, we are able to update the quote value to the current value with the random index by using the getRandomIndex function.

We will be passing on the properties of the useState and setState hooks to the child Component, which is the QuoteBox Component, when the App is rendered.

We also need to style the App with the background colors by using the Math.random function  using the entire length of the backgroundColors array that we created earlier to store all the background colors.

When the above App is rendered, it will return the QuoteBox  component wrapped in a div class of wrapper to wrap all the items of the QuoteBox. 
The  parent  Component is the App Component that passes the property  of handleNewQuote , setQuote, and useState to it's child component, QuoteBox. 

Passing State properties from the App Component to child Component QuoteBox:

Every time, the parent App Component  is rendered, through the passed state properties to its child component QuoteBox,  whereby the useState property will help to track the state of the quote from the initial  state  and shows the current value of the quote with the help of setQuote property that will update the value of the quote when we trigger the handleNewQuote function that will add the value of current quote with random index when the user clicks on the New quote button. so now, we know how to pass state properties from parent component  to child component in ReactJS. 

Perform the ReactDOM.render() method to render the App to the web:

In order to render this React app to the web page, we need to perform the ReactDOM.render() function that takes two parameters : an element that we want to render (in this case it is the App that we want to render ) and a container(in this case, it is the container div with an id of 'app') where we want the app to render. This is represented in the final line of our code as mentioned in the code below : 
ReactDOM.render(<App />,  document.querySelector("#app"))

How to add the React library in the JSitor code editor:

When you click in the library tab of this code editor, you will need to choose the following options in the Add Library drop-down options :
  1. create-react-class
  2. react.development
  3. react-dom.development
  4. babel.min.js
  5. react-dom.production
  6. react-js.production

Once you add the above React library to the code editor , you don't need to import any library while coding, the editor will take care of it in the background, since this is a cloud editor.

How to add the React library in CodePen:

When you are in the JavaScript file, just click on the settings key and go to the JavaScript Preprocessor, here , you will find drop-down options, just choose 'Babel'. Then go down to the section right below the JavaScript Preprocessor section, where you will find the 'Add External Scripts/Pens section- here in the search query, just key in 'React' and you will find the url of the React library appear in the search box, and just need to click on that and you are done adding the React library once you save this settings.


The code for JavaScript file:
const quoteData = [
  {
    text: "The elevator to success is out of order. You’ll have to use the stairs, one step at a time.",
    author:"Joe Girard"
  },
  {
    text: "People often say that motivation doesn’t last. Well, neither does bathing – that’s why we recommend it daily.",
    author:"Zig Ziglar"
  },
  {
    text: "I always wanted to be somebody, but now I realise I should have been more specific.",
    author:"Lily Tomlin"
  },
  {
    text: "I am so clever that sometimes I don’t understand a single word of what I am saying",
    author:"Oscar Wilde"
  },
  {
    text: "People say nothing is impossible, but I do nothing every day.",
    author:"Winne the Pooh"
  },
  {
    text: "Life is like a sewer… what you get out of it depends on what you put into it.",
    author:"Tom Lehrer"
  },
  {
    text: "You can’t have everything. Where would you put it?",
    author:"Steven Wright"
  },
  {
    text: "Work until your bank account looks like a phone number.",
    author:"Unknown"
  },
  {
    text: "Change is not a four letter word… but often your reaction to it is!",
    author:"Jeffrey Gitomer"
  },
  
{
    text: "People often say that motivation doesn’t last. Well, neither does bathing – that’s why we recommend it daily.",
    author:"Zig Ziglar"
  },
  {
    text: "I always wanted to be somebody, but now I realise I should have been more specific.",
    author:"Lily Tomlin"
  },
  {
    text: "I am so clever that sometimes I don’t understand a single word of what I am saying",
    author:"Oscar Wilde"
  },
  {
    text: "People say nothing is impossible, but I do nothing every day.",
    author:"Winne the Pooh"
  },
  {
    text: "Life is like a sewer… what you get out of it depends on what you put into it.",
    author:"Tom Lehrer"
  },
  {
    text: "You can’t have everything. Where would you put it?",
    author:"Steven Wright"
  },
  {
    text: "Work until your bank account looks like a phone number.",
    author:"Unknown"
  },
  {
    text: "Change is not a four letter word… but often your reaction to it is!",
    author:"Jeffrey Gitomer"
  },
  {
    text: "If you think you are too small to make a difference, try sleeping with a mosquito.",
    author:"Dalai Lama"
  },
  
{
    text: "People often say that motivation doesn’t last. Well, neither does bathing – that’s why we recommend it daily.",
    author:"Zig Ziglar"
  },
  {
    text: "I always wanted to be somebody, but now I realise I should have been more specific.",
    author:"Lily Tomlin"
  },
  {
    text: "I am so clever that sometimes I don’t understand a single word of what I am saying",
    author:"Oscar Wilde"
  },
  {
    text: "People say nothing is impossible, but I do nothing every day.",
    author:"Winne the Pooh"
  },
  {
    text: "Life is like a sewer… what you get out of it depends on what you put into it.",
    author:"Tom Lehrer"
  },
  {
    text: "You can’t have everything. Where would you put it?",
    author:"Steven Wright"
  },
  {
    text: "Work until your bank account looks like a phone number.",
    author:"Unknown"
  },
  {
    text: "Change is not a four letter word… but often your reaction to it is!",
    author:"Jeffrey Gitomer"
  },
  {
    text: "If you think you are too small to make a difference, try sleeping with a mosquito.",
    author:"Dalai Lama"
  },
  
{
    text: "People often say that motivation doesn’t last. Well, neither does bathing – that’s why we recommend it daily.",
    author:"Zig Ziglar"
  },
  {
    text: "I always wanted to be somebody, but now I realise I should have been more specific.",
    author:"Lily Tomlin"
  },
  {
    text: "I am so clever that sometimes I don’t understand a single word of what I am saying",
    author:"Oscar Wilde"
  },
  {
    text: "People say nothing is impossible, but I do nothing every day.",
    author:"Winne the Pooh"
  },
  {
    text: "Life is like a sewer… what you get out of it depends on what you put into it.",
    author:"Tom Lehrer"
  },
  {
    text: "You can’t have everything. Where would you put it?",
    author:"Steven Wright"
  },
  {
    text: "Work until your bank account looks like a phone number.",
    author:"Unknown"
  },
  {
    text: "Change is not a four letter word… but often your reaction to it is!",
    author:"Jeffrey Gitomer"
  }
];;
const backgroundColors = ["#F0F8FF",
"#FAEBD7","#00FFFF","#7FFFD4","#FFE4C4","#000000","#FFEBCD","#0000FF","#8A2BE2","#A52A2A","#DEB887","#5F9EA0","#7FFF00","#D2691E","#FF7F50","#6495ED","#DC143C","#00FFFF","#00008B","#008B8B","#8B008B","#556B2F","#9932CC","#8B0000","#483D8B","#00CED1","#9400D3","#FF1493","#1E90FF","#FF00FF","#FF69B4","#00FF00","#0000CD","#4169E1","#2E8B57","#008080","#FFFF00","#FF6347","#D8BFD8","#9ACD32","#6A5ACD","#FA8072","#DDA0DD","#800080","#CD853F","#AFEEEE","#FF4500","#C71585","#191970","#BA55D3","#20B2AA"];

/*const backgroundColors = ["blue","red","pink","brown","yellow","green", "magenta"];*/
const QuoteBox = ({ quotehandleNewQuote }) => (
  <div id="quote-box">
    <p id="text">{quote.text}</p>  
    <h2 id="author">{quote.author}</h2>
    <div class="click">
      <button 
        id="new-quote" 
        class="btn"
        onClick={handleNewQuote
        >
        New Quote
      </button>
      <a 
         href="https://twitter.com/intent/tweet"
         id="tweet-quote"
         target="_blank"
       >
         Tweet
      </a>
    </div>
  </div>
);



/*const getRandomIndex = (max) => 
  Math.round(Math.random() * ((quoteData.length-1) - 0) + 0);*/

const getRandomIndex = (max) => 
  Math.floor(Math.random() * (quoteData.length));


const App = () => {
  const [quotesetQuote= React.useState(quoteData[getRandomIndex()])

  const handleNewQuote = () => {
    setQuote(quoteData[getRandomIndex()])
  }
  document.body.style.backgroundColor = backgroundColors[Math.floor(Math.random()*backgroundColors.length)];

  return (
    <div class="wrapper">
      <QuoteBox handleNewQuote={handleNewQuotequote={quote/>
    </div>
  )
}


ReactDOM.render(<App />document.querySelector("#app"));




The code for CSS : 















  

* {
  margin: 0;
  padding: 0;
  box-sizing:border-box;
}


h2 {
  font-size: 19px;
  margin: 25px, 0;
  color: whitesmoke;
}

p {
  margin: 0;
  font-size: 16px;
  color:whitesmoke;
}

body {
    display: flex;
    width: 100vw;
    height: 100vh;
    justify-content: center;
    align-items: center;
    margin:auto;
    
}

    
    

#quote-box {
    width: 340px;
    padding: 40px;
    border-radius: 10px;
    display:block;
  background:black;
  margin:auto;
}

.click {
    display: flex;
    align-items: center;
}

.wrapper .btn,
#tweet-quote{
    background:darkblue;
        display: flex;
    border-radius: 7px;
    padding: 7px 11px;
    cursor: pointer;
    font-size: 10px;
    color: whitesmoke;
  align-items:center;
  margin:25px 25px 25px;
  margin-bottom:-10px;
  margin-left:-7px;
  justify-content:center;
  
}

#tweet-quote {
    margin-left: 7px;
    padding: 9px 15px;
    text-decoration: none;
  border:white;
  border-radius: 7px;
  
}





















The CSS code explanation:
As you can see in the above css code, I have used minimal css code here to style the App.
The margin and padding values have been set to  0 in order to reset any default padding or margin of the page. Since we set the box-sizing to the value of border-box, the box-sizing property permits us to include the padding and border in the width and height of the element to which this property is added.

If you have built your app after reading this detailed tutorial, to see how the Random Quote Machine performs, you can run your app after seeing how it looks in Live View.

For full source code, you may either refer to the code above or view my source code for this project at my GitHub repository. My GitHub profile id is meeramenon07.

If you wish to watch a video tutorial for this challenge , here is the  Video tutorial below.







Other React Projects Guides:


Some Related Posts that you may find useful:


Comments

Popular Posts

A Simple Guide to Promises in JavaScript ES6

Welcome to my first Blog Post

How To Fight Programmer's Imposter Syndrome

Top Free Online Websites to Learn Coding

Build A Calculator in React

What Programming Language Should You Learn First As A Beginner?