Lalas M
Lalas M

Reputation: 1174

How to pass values to a page while clicking on dynamically generated 'Link' in ReactJs?

I have an array of elements (eg. urls_array) and using this array I dynamically create links to a page. How do I pass corresponding values from this array to the page(destination) while clicking on the dynamically created Links?

1 - Leftnav.js


class Leftnav extends React.Component {
  render() {

    var urls_array = [
      url1,
      url2,
      url3
    ] 

    return (
      <div className="container">
        <SideNavMenu title="Dynamically Generated">
            {
                urls_array.map(links => (
                <SideNavMenuItem key={links} element={Link} to="/singlepage" >{links.toString()}</SideNavMenuItem>
                ))
            }
        </SideNavMenu>
      </div>
    )
  }
}

export default Leftnav;

The above code will create three links url1, url2 and url3 and when clicking any of these links we wil be redirected to a singlepage.

2 - singlepage.js

class singlepage extends React.Component {
    render() {
        return (
            <React.Fragment>
            </React.Fragment>
        );
    }
}    
export default singlepage;

What I'm trying to achieve here is while clicking on the url1 I need (value of) url1 in the singlepage, if I click on url2 I'm expecting url2 in the singlepage and so on.

Upvotes: 1

Views: 101

Answers (2)

Dixit Savaliya
Dixit Savaliya

Reputation: 413

Try this,

<Link to={{ pathname: `/componentname`, state: { data: yourdata }}}></Link>

Upvotes: 0

tarzen chugh
tarzen chugh

Reputation: 11247

Just pass the data in state inside to

<Link
  to={{
    pathname: "/singlepage",
    state: { links }
  }}
/>

and access in singlepage component using this.props.location.state.links

Hope that helps!!!

Upvotes: 2

Related Questions