React Fetch API quote random generator

share link

by vsasikalabe dot icon Updated: Feb 17, 2023

technology logo
technology logo

Solution Kit Solution Kit  

Everyone has their favorite quote(s) they love to tell people or post about on their social media (like Facebook) to cherish forever! We are using the quote function from the quote module to generate a random quote. To search for the quotes, the quote function requires a keyword. 


We also need to set the limit value to limit the number of quotes being generated. A handleClick method is an instance method that changes the local state in the toggle class.this.handleClick is passed as an event handler to the button in the render method. At last, we have to bind this to handleClick in the constructor. The Fetch API gives an interface for fetching resources. The Quote Box content type allows you to create a quote with a graphical treatment for your website. 

You can see three things when you go to the link: 

  • we have our quotes array that contains 
  • a key quote 
  • a key of the author 

Now, we can fetch some data from our API.  


Here is an example of how to fetch API quote random generator using Reactjs: 

Preview of the output that you will get on running this code from your IDE.

Code:

In this solution we use the React library and handle click function.

class QuoteBox extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      quoteData: [],
      quote: '',
      author: ''
    }
    this.randomQuote = this.randomQuote.bind(this);
    this.handleClick = this.handleClick.bind(this);
  }

  componentDidMount() {
    const API = 'https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/'
    fetch(API)
        .then((response) => response.json())
        .then((data) => {
            this.setState({
              quoteData: data.quotes
            },()=>{
              // add handle click function here, so that a random quote in shown on initial load
              this.handleClick();
            })
        })
        .catch(error => console.log('Error', error));
        // remove randomQuote() call from here, there is no use of that call here.

  }

  randomQuote() {
    const randomNumber = Math.floor(Math.random() * this.state.quoteData.length);
    return this.state.quoteData[randomNumber];
  }

  handleClick() {
    const oneRandomQuote = this.randomQuote();
    this.setState({
      quote: oneRandomQuote.quote,
      author: oneRandomQuote.author
    })
  }

  render() {
    return (
      <div id='quote-box'>
        <h1 id='text'>
          {this.state.quote}
        </h1>
        <h3 id='author'>
          - {this.state.author}
        </h3>
        <Buttons handleClick={this.handleClick}/>
      </div>
    )
  }
}

class Buttons extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return(
      <div className='buttons'>
        <a id='tweet-quote' className='button' href={`https://twitter.com/intent/tweet/?text=${this.props.quote} - ${this.props.author}`}><i className='fab fa-twitter'></i></a>
        <button id='new-quote' className='button' onClick={this.props.handleClick}>
          New quote
        </button>
      </div>
    )
  }
}

Instructions

Follow the steps carefully to get the output easily.

  1. Install the Node.js and React on your IDE(preferable Visual Studio Code).
  2. Create React Application using npx create-react-app foldername.
  3. cd foldername.
  4. Open the folder in IDE.
  5. Copy the code using "copy" button above and paste it in App.js file(remove the earlier code from App.js).
  6. Import Libraries.
  7. Open the terminal from IDE.
  8. npm start to run the file.


I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.


I found this code snippet by searching for React Fetch API quote random generator in kandi. You can try any such use case!

Environment Tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. The solution is created in VS Code 1.73.1 version.
  2. The solution is tested on Nodejs 16.14.2 version.
  3. react 18.2.0 version.


Using this solution, we are able to fetch API quote random generator using react with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to fetch API quote random generator using react.

Dependent Libraries

create-react-appby facebook

JavaScript doticonstar image 100082 doticonVersion:v5.0.1doticon
License: Permissive (MIT)

Set up a modern web app by running one command.

Support
    Quality
      Security
        License
          Reuse

            create-react-appby facebook

            JavaScript doticon star image 100082 doticonVersion:v5.0.1doticon License: Permissive (MIT)

            Set up a modern web app by running one command.
            Support
              Quality
                Security
                  License
                    Reuse

                      You can search for any dependent library on kandi like react.

                      Support

                      1. For any support on kandi solution kits, please use the chat
                      2. For further learning resources, visit the Open Weaver Community learning page.

                      See similar Kits and Libraries