1

So basically I have this issue. I'm relatively new to React JS. I've created a state and I've successfully mapped it except for one thing. Below is the state:

const [currProject, setCurrProject] = useState([{
            id: 4,
            title: "Title",
            desc: "Description",
            arr: ["these", "are", "array", "elements"]}]);

So then, like I said, I map this like so:

currProject.map(item =>(
     <div>
          <h1>{item.title}</h1>
          <p>{item.desc}</p>
          <div>
               <p>{item.arr}</p>
          </div>
     </div>
        ))

So basically where the p tag is, I want to put the elements in the array in the currProject state in separate p tags. So it would look something like this:

<p>these</p>
<p>are</p>
<p>array</p>
<p>elements</p>

But obviously I wouldn't want to hard code that. Because that array could have more or less elements in it. Basically what I'm asking is how do I map an array that's already inside a state array?

0

2 Answers 2

3

You can map it just like you mapped the previous array.

    currProject.map((item, i) =>(
         <div key={i}>
              <h1>{item.title}</h1>
              <p>{item.desc}</p>
              <div>
                   {item.arr.map((item, i) => (
                    <p key={i}>{item}</p>
                   ))}
              </div>
         </div>
        ))
Sign up to request clarification or add additional context in comments.

Comments

2

You need use more map to render item.arr.

  {currProject.map((item) => (
    <div key={item.id}>
      <h1>{item.title}</h1>
      <p>{item.desc}</p>
      <div>
        {item.arr.map((item2, index) => (
          <p key={index}>{item2}</p>
        ))}
      </div>
    </div>
  ))}

Note: You need add a key in fist tag inside map

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.