简体   繁体   中英

How to pass props to another component with <Link> in React Router

I'm using an array to display set of search results and on clicking one item, I want to pass the item as props, and not as params.

Here is my code:

{ this.props.results.map((result) => {              //Fetching Each Element
                return (
                    <li key={ result._source.file_name }>
                        <Link to={{pathname: '/photo/' + result._source.file_name + '/' + result._source.keywords, state: { modal: true }}}>
                            <img src={'/photos/' + result._source.file_name} className="image grow-shadow" alt="Search Result" />
                        </Link>
                    </li>
                ) }) }  

I want to pass key={result._source.keywords} as props and not as params in route like

<Route path='/photo/:id/:keyw' component={Single} />

This will make URL look ugly.

How can i achieve that?

The link can be structured as follows:

<Link to={{pathname: '/photo/:id', state: {keyw: result._source.keywords}}></Link>

In the component, you can access the state as follows:

this.props.location.state.keyw

Passing state through the Link itself uses the HTML5 history state object which should be persisted across refreshes.

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