2

I am a beginner in React. I am using the json placeholder to fetch data using axios. I have two arrays in the state.

state = {
                posts : [],
                images : []

       };

After getting the data through axios I am using set state up update the value. Now, I want it all displayed in a card. If it were just one array I would've used map to display the content. Now I want an image from the images array to be displayed with each post. How could I go about this?

2
  • 3
    Why not combine both arrays into one and have a data object in the array that holds the post and it's image? Commented Apr 11, 2020 at 16:07
  • posts.map((item, index)=> {const image = images[index]; ...}) Commented Apr 11, 2020 at 16:11

2 Answers 2

3

You can create single array out of two array in this way.

const postsWithImage=this.state.posts.map(post=>{
return {
...post,
img: this.state.images.find(img=> img.id===post.imgid) // or some relation between posts and images
}

})

now further map the postsWithImage

Sign up to request clarification or add additional context in comments.

Comments

2

instead of separate arrays you could combine them and loop through like this :

const renderPosts = ()=>{
  return this.state.posts.map(post,index=>{
      return(
          <Card
             postImage={post.image}
             postData={post.data}
          />
       )
})
}

But if you are insisting on keeping them separate than you could do a nested loop like :

const templates = {
  template1: {
    items: [1, 2]
  },
  template2: {
    items: [2, 3, 4]
  },
};

const App = () => (
  <div>
    {
      Object.keys(templates).map(template_name => {
        return (
          <div>
            <div>{template_name}</div>
            {
              templates[template_name].items.map(item => {
                return(<div>{item}</div>)
              })
            }
          </div>
        )
      })
    }
  </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.