kandi background
Explore Kits

React Fetch API quote random generator

by vsasikalabe Updated: Jan 24, 2023

To generate a random quote we will be using the quote function from the quote module. The quote function requires a keyword to search for the quotes. We also set the limit value to limit the no of quotes being generated.In the Toggle class, a handleClick method is defined as an instance method, which changes the local state. In the render method, this. handleClick is passed to the button as an event handler. Finally, do not forget to bind this to handleClick in the constructor.The Fetch API provides an interface for fetching resources (including across the network).The Quote Box content type allows you include a quote with a graphical treatment to your website.

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.

Lines of Code : 75License : CC BY-SA 4.0

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 star image 98671 Version:v5.0.1

License: Permissive (MIT)

Set up a modern web app by running one command.

Support
Quality
Security
License
Reuse

create-react-appby facebook

JavaScript star image 98671 Version:v5.0.1 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

JavaScript