How can I pass props through an anchor tag?

Viewed 1183

I want to know, how can I pass props to other component? Something like objectid={top.id} through an anchor tag.

{lists.map((top) => {
       return (
            <li key={id}>
               <a href={'/object/'+ slugify(top.title) } objectid={top.id}>
                 <img alt={top.title} src={top.image-url}/>
               </a>
            </li>
       )})
}

I want to pass {top.id} to the component which will be rendered on going to url from href given and there I can access it like props.objectid

2 Answers

For the image, you cannot have src={top.image-url}. You need to use src={top["image-url"]} else it won't work.

And if you're using React Router, please use the React Router: Link component for this.

<Link
  to={{
    pathname: `/object/${slugify(top.title)}`,
    state: { objectId: top.id }
  }}
>
  <img alt={top.title} src={top["image-url"]} />
</Link>

Here you can also set the Link state, so that it can be accessible in the other page too, so as from which page this has come from, etc.

Better to use react-router Link

  <Link to={{
     pathname: `/object/${slugify(top.title)}`,
     state: top.id  
  }} objectid={top.id}>
   <img alt={top.title} src={top.image-url}/>
  </Link>
Related