Search code examples
javascriptreactjsreact-nativefetch

How can I display all the objects of array from fetch in div?


How do I save my array of objects in a proper way? and then display them in html? Console log can print the whole array but it does not work the same in html

import React from "react";
import "./style.css";
class App extends React.Component {
  constructor() {
    super();
    this.state = {
      quotes: [],
    };
  }

  componentDidMount() {
    fetch("https://type.fit/api/quotes")
      .then((response) => response.json())
      .then((data) => this.setState({ quotes: data }));
  }

  render() {
    console.log(this.state.quotes.text);
    return (
      <div>
        <h1>{this.state.quotes[0].author}</h1>
      </div>
    );
  }
}

export default App;

Solution

  • You can map through the quotes in the JSX.

    return (
       <div>
         {this.state.quotes && this.state.quotes.map(quote => (
           <div>
             <h1>{quote.author}</h1>
             <p>{quote.content}</p>
           </div>
         ))}
       </div>
     );
    

    Tell me if I misunderstood something or if it helps :)