skip to Main Content

I am a beginner in React and today I stumbled upon a problem, perhaps I could use some help.

The Home component needs to display a card with data brought in from an API.

This is what I did:

<div>
            {
                allRecipes?.map((e) => {
                    return (
                        <div>
                            <Link to={"/home" + e.id}>
                                <Card title={e.title}/>
                            </Link>
                        </div>
                    )
                })
            }
        </div>

I was expecting it to render a Card with in this case for brevity the title of a cooking recipe, this did not work and it’s not being rendered.

I will share a link source of my GitHub repo: Click here

3

Answers


  1. The issue might be with the usage of the Link component.

    Try this:

    1. Make sure to import the Link component and provide a valid URL path for the to prop.

    2. Include a unique key prop to the outer div element. The key prop helps to efficiently update and manage the list of elements. You can use a unique identifier like the id property of each recipe as the key value.

       import { Link } from 'react-router-dom';
      
       // ...
      
      <div>
      {
        allRecipes?.map((recipe) => (
          <div key={recipe.id}> {/* Added a unique "key" prop */}
             <Link to={"/home/" + recipe.id}> {/* Adjusted the link URL */}
                 <Card title={recipe.title} /> 
             </Link>
         </div>
      ))
      }
      </div>
      
    Login or Signup to reply.
  2. A small correction might work for you.

    <div>
                {
                    allRecipes?.map((e) =>  (
                            <div>
                                <Link to={"/home" + e.id}>
                                    <Card title={e.title}/>
                                </Link>
                            </div>
                        )
                    )
                }
            </div>
    
    Login or Signup to reply.
  3. your main code problem is only type e.id is not working

    try this

    {

           Array.isArray(allRecipes) ? allRecipes?.map((e) => {
                    return (
                        <div>
                            <Link to={"/home" + {e?.id}>
                                <Card title={e?.title}/>
                            </Link>
                        </div>
                    )
                }) : return <div> data is empty </div>
            }
        </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search