0

I want to show the blog author and blog title in the array on my html page but nothing is displayed. I used the map method and it worked but the forEach method shows nothing. I will like a solution in for loop and forEach loop Here is my code:

import { useState } from "react";

const Home = () => {

const [blogs, setBlogs] = useState([
    { title: 'My new website', body: 'lorem ipsum...', author: 'mario', id: 1 },
    { title: 'Welcome party!', body: 'lorem ipsum...', author: 'yoshi', id: 2 },
    { title: 'Web dev top tips', body: 'lorem ipsum...', author: 'mario', id: 3 }
]);


return ( 
    <div className="home">
      

         {blogs.forEach((blog) => {
            <div className="blog-preview" key={blog.id}>
                <h2>{ blog.title }</h2>
                <p>Written by{ blog.author }</p>
            </div>
        })} 
       
    </div>
      
 );
 }export default Home;
Ademola
  • 9
  • 3

3 Answers3

0

Try it with map.
{blogs.map((blog) => {<div className="blog-preview" key={blog.id}><h2>{ blog.title }</h2><p>Written by{ blog.author }</p></div>})}

krani
  • 37
  • 4
0

I usually prefer to use .map for this like

blogs.map((blog) => (
      <div> //your code </div>
    ))
mocha
  • 45
  • 6
0

Use map instead because the map method returns a new array by applying the callback function on each element of an array, while the forEach method doesn't return anything.

so you have to use it like this.

{blogs.map((blog) => {
            <div className="blog-preview" key={blog.id}>
                <h2>{ blog.title }</h2>
                <p>Written by{ blog.author }</p>
            </div>
        })} 

like this.