Build a Random Quote Machine with React
Tags: javascript, react, codenewbie, beginners
Published: 2020-06-14 13:49:33

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/fbnec436h5lhg9dqv0f4.png)

Click here to view the [Demo](https://react-random-quote-generator.netlify.app/)

This tutorial is about how to build a simple Random Quote generator using React and to be able to share the quote on twitter.
The goal of this tutorial is to show how to use React state and Function to create a simple react app.

#App Folder Structure

Using _Create-react-app_ , we will create a boilerplate that will create the Public folder, this will contain the index.html file, the _src_ folder that will contain the component folder . On the root level of the src folder we will have the _index.js_ and _App.js_ file . This app will have only the frontend. The database will be at the root of the _src_ folder named _QuoteDB.js_. We will be using bootstrap cdn and font awesome cdn .

Creating React app
------------------
The fastest way of creating a react app is using the command _npx create-react-app_ random-quote . This will create the boilerplate to get our files ready.

App Component
-------------
Inside the src folder is the App.js file that was created using _create-react-app_ , but we will now modify it to suit our purpose . First we create a folder called components and inside it we also create just one file called _QuoteAndAuthor.js_ . We are using components folder just for the purpose of learning . We could have created all files needed on the root of _src_ folder.

In the _App.js_ we will create a state object with the quote and Author as properties and the _generateRandomQuote_ function that will generate the quotes at random. We will remember to import _react_ from react, _QuoteAndAuthor.js_ from the components folder and also import the Database from root of the _src_ folder. We will create both files later.

We also have the _shuffleQuote_ function that helps to randomize the quote at different clicks. The last thing we will do on the _App.js_ is to return the _QuoteAndAuthor.js_ component with the _generateRandomQuote_ function and state object
```react
import React, { Component } from 'react'
import QuoteAndAuthor from './components/QuoteAndAuthor';
import quotes from './QuoteDB';

export default class App extends Component {

  //state
  state = {
    quote: quotes[0].quote,
    author: quotes[0].author
  }

  //generate diffrent quote function
  generateRandomQuote = (arr) => {
    //get random numbers
    let num = Math.floor(Math.random() * quotes.length)

    let newQuote = quotes[num];

    //update state
    this.setState({
      quote: newQuote.quote,
      author: newQuote.author
    })

    this.shuffleQuotes(quotes)

  }

  //shuufle quotes function
  shuffleQuotes = (arr) => {
    return arr.sort(function () { return 0.5 - Math.random() });
  }

  render() {
    return (
      <div className="container">
        <h1 className="text-center">Random Quote</h1>
        <QuoteAndAuthor
          generateRandomQuote={this.generateRandomQuote}
          quote={this.state}
        />
      </div>
    )
  }
}
```
Index.js
--------
No changes will be done on the _index.js_ file, we will use the default created by the _create-react-app_ boilerplate
```react
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

serviceWorker.unregister();
```
Index.html
----------
_Index.html_ is in the public folder, the only change we will do is adding the bootstrap and font awesome cdn links
```html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="theme-color" content="#000000" />
  <meta name="description" content="Web site created using create-react-app" />
  <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
  <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
  <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

  <!-- bootstrap-->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
    integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  <title>Quote Generator - React App</title>
</head>

<body>
  <noscript>You need to enable JavaScript to run this app.</noscript>
  <div id="root"></div>

  <!--font awesome-->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/js/all.min.js"></script>

  <!-- bootstrap-->
  <script src="https://code.jquery.com/jquery-3.5.0.js" integrity="sha256-r/AaFHrszJtwpe+tHyNi/XCfMxYpbsRg2Uqn0x3s2zc="
    crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
    integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
    crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
    integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
    crossorigin="anonymous"></script>
</body>

</html>
```
QuoteAndAuthor.js
-----------------
In _QuoteAndAuthor.js_ file first, we will import both react and the database. Here we will be using react function as we will only be displaying the output from _App.js_ file.
In _QuoteAndAuthor.js_ file, we will need to pass in _props_ to the _QuoteAndAuthor_ function as this is not passed by default and then destructure quote and _generateRandomQuote_ so that we have access to them. 
Note that we have two buttons. One to generate the Quotes and the other button to share the quote on twitter.
```react
import React from 'react'
import quotes from '../QuoteDB'

export default function QuoteAndAuthor(props) {

    const { quote, generateRandomQuote } = props;
    return (
        <div className="card" >

            <div className="card-body">
                <p className="card-text">{quote.quote}</p>
                <h5 className="card-title">- {quote.author}</h5>
                <button
                    onClick={() => { generateRandomQuote(quotes) }}
                    type="submit">
                    <i class="fas fa-mouse"></i> Generate Quote</button>
                <button
                    className="ml-3"
                    onClick={() => {
                        generateRandomQuote(quotes);
                        window.open('https://twitter.com/intent/tweet/?text=' + encodeURIComponent(quote.quote + '--' + quote.author))
                    }}
                    type="submit"><i class="fab fa-twitter"></i> Share Quote</button>
            </div>
        </div>
    )
}
```
Database
--------
 For this project, our database is in _QuoteDB.js_ file and just an array with objects. We will also need to export this file so that other components and file will be able to access it.
```javascript
const quotes = [
    {
        "quote": "Forget all the reasons why it won't work and believe the one reason why it will",
        "author": "Unknown"
    },
    {
        "quote": "Always do what you are afraid to do",
        "author": "Ralph Waldo Emerson"
    },

    {
        "quote": "Don’t be intimidated by what you don’t know. That can be your greatest strength and ensure that you do things differently from everyone else.",
        "author": "Sara Blakely"
    },
    {
        "quote": "If you keep on doing what you've always done, you will keep getting what you've always gotten.",
        "author": "Unknown"
    },
    {
        "quote": " For God so loved the world that he gave his one and only Son, that whoever believes in him shall not perish but have eternal life. John 3:16",
        "author": "Jesus Christ"
    },
    {
        "quote": "The surest way to find your dream job is to create it.",
        "author": "Unknown"

    }
]

export default quotes;
```
##Conclusion: Build a Random Quote Machine with React
We are able to create a simple random quote machine using _create-react-app_. Some of the things we learnt include creating react app using the _npx create-react-app_ that creates for us the boilerplate. In _App.js_, we used  react state component and react functional component in _QuoteAndAuthor.js_ to output our quotes and authors, and created a function to generate quotes . 

We also created a _QuoteDB.js_ file which host all our quotes and used font awesome for icons. Congratulations we successfully created a Quote Generator!. To start the App, we run _npm start_. Happy coding!
Git repo [here](https://github.com/thinkC/react-randomquote-generator)

Cover Photo by Nathan Lemon on Unsplash
{% user thinkc %}