Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 14, 2020 01:49 pm GMT

Build a Random Quote Machine with React

Alt Text

Click here to view the Demo

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

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

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

<!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/[email protected]/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.

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.

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": "Dont be intimidated by what you dont 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!.

Cover Photo by Nathan Lemon on Unsplash

.ltag__user__id__406226 .follow-action-button { background-color: #093656 !important; color: #ffffff !important; border-color: #093656 !important; }
thinkc image

Original Link: https://dev.to/thinkc/build-a-random-quote-machine-with-react-41p4

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To