Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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']},
]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading