2

Hello I have some data I am trying to display with react that looks like this

snapshot

there is an Options array inside of the Poll array. How do I display the options array with react when I am already mapping the Poll array? This is what i have so far:

renderPost(posts){

        return posts.map((post) => {
        return (
            <div>
            <h3>{post.question}</h3>


            </div>
               );
        });
    }
0

2 Answers 2

3

Something like

renderPost(posts){
  return posts.map(post =>
    <div>
      <h3>{post.question}</h3>
      <ul>
        {post.options.map(option => 
          <li>{option.title}</li>
        )}
      </ul>
    </div>
  )
}
Sign up to request clarification or add additional context in comments.

2 Comments

hey thanks for the reply but im getting "Cannot read property 'map' of undefined"
I had to guess at your data model, you’ll need to adapt it to your specific needs
0

You should never forget add a key to the jsx element when generate them in loop. The key should be unique and key should be from data, if your data doesn't contain unique id per object then use index as a key like below

Unique id as key from data

return posts.map(post =>
    <div key={post.id}>
      <h3>{post.question}</h3>
      <ul>
        {post.options.map(option => 
          <li key={option.id}>{option.title}</li>
        )}
      </ul>
    </div>
  )

Use index as a key if you don't have unique id in data array

return posts.map((post, index) =>
    <div key={`Key${index}`}>
      <h3>{post.question}</h3>
      <ul>
        {post.options.map((option, i) => 
          <li key={`Key${i}`}>{option.title}</li>
        )}
      </ul>
    </div>
  )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.