简体   繁体   中英

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.

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!!!

Try this,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM