Home > Software design >  Issue rendering list in React Component using API
Issue rendering list in React Component using API

Time:04-14

The code below is a component I am using to show the title of the posts based on what I get from the link. Everything with the API seems to work well, but I am not getting the list rendered for posts.forEach(post => <li id={post.id}> {post.title} </li>. Can anyone know how can I render the post title as a list from an array posts I get from an API? Thank You for helping, and let me know if you need more information.

import React, { useState, useEffect } from "react";
import axios from "axios";

const DataFetch = () => {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    axios
      .get("https://jsonplaceholder.typicode.com/posts")
      .then((res) => {
        setPosts(res.data);
        console.log(posts[0].title);
      })
      .catch((err) => console.log(err));
  }, []);

  return <ul>
    {  posts.forEach(post => <li id={post.id}> {post.title} </li> )}
  </ul>
};

export default DataFetch;

CodePudding user response:

Array.prototype.forEach is a void return. You want to map the posts to JSX. Don't forget to also map a React key.

posts.map(post => (
  <li key={post.id} id={post.id}>
    {post.title}
  </li>
))
  • Related