Home > database >  React: Passing array from state as props only reads the first element of an array
React: Passing array from state as props only reads the first element of an array

Time:08-28

I have two components. First, I have the parent component, where I state variable that is an array.

    import react, {useState} from 'react';
import Posts from './Posts';

function App() {
  const [posts, setPosts] = [
    {title: 'post1',comments:['comment1', 'comment2','comment3']},
    {title: 'post1',comments:['comment1', 'comment2','comment3']},
    {title: 'post1',comments:['comment1', 'comment2','comment3']},
  ]

  return (
    <>
      <h1>Parent Component</h1>
      <Posts posts={posts}  />
    </>
  );
}

export default App;

Then in my second component, I read in those props, but I only get the first value in the array when I console.log(posts), and when I try to use the map method on the posts props.

    import React from 'react'

export default function Posts({posts}) {
    console.log('posts: ', posts)
  return (
    <>
    <h2>Posts</h2>
    {posts.map((post, index)=>{
        return(
            <div key={post.title}>
            <h3>{post.title}</h3>
           
            </div>)}
        )
        
    })
    </>
    
  )
}

What am I doing wrong here?

CodePudding user response:

Seems that you forgot to call useState():

const [posts, setPosts] = useState([
  {title: 'post1',comments:['comment1', 'comment2','comment3']},
  {title: 'post1',comments:['comment1', 'comment2','comment3']},
  {title: 'post1',comments:['comment1', 'comment2','comment3']},
]);
  • Related