skip to Main Content

I’m new to learning React and passing props to child components is still confusing to me.

I passed an array of objects from Express server to React app with axios.

The React app first uses .stringify() and then uses .parse() and then I updated the state variable:

enter image description here

Outside the useEffect and within the return statement when I try to access the books useState variable, I can only console.log its values, but it doesn’t render when I map and try to pass it to a child component:

enter image description here

This is the Book Component:

enter image description here

What is causing it to not render?

I’ve tried different ways to iterate through and also rendered the book component by itself and it renders then, but doesn’t render when I pass it the objects values.

2

Answers


  1. first of all check your api response.
    if you have api response.
    you must check your state data like this

    useEffect(()=>{
        console.log("my books", books)
    },[books])
    

    if your books have a data

    you should add key for your books element like this

    books.map((book,index)=>{
        return <Book key={book.id //or you can use inedx} price={book.price} name={book.name}/>
    
    
    })
    
    Login or Signup to reply.
  2. What is causing it not to render?

    Have you checked your mapping callback??
    a callback to map method required to return a value. if the callback doesn’t return any value by default it will return undefined.
    So after your mapping for the book it is simply an array of undefined.
    This is the main reason why it is not rendering your book component.
    Here is the updated version of your mapping callback

    books.map((b,index)=>{
         return <Book
          // i assume name + index will  create some unique key :)
          key={b.name+index}
          Name={b.Name}
          Price={b.Price}
          Url={b.Url}
        />
     })
    

    I hope this will help 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search