Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router, pass props with Link

Im using React Router to navigate to a page in my app like this:

<Link to={`/single/${this.props.data.pageId}`} params={{singleId: 1}}>GotoPage!</Link>

This works fine but I would also like to pass an additional property to the new page.

When rendering a component without using Link I would do something like:

<MyComponent myProp={this.props.data}/>

I have tried passing myProp={this.props.data} along in params like this:

<Link to={`/single/${this.props.data.pageId}`} params={{singleId: 1, myProp={this.props.data}}}>GotoPage!</Link>

But it does not seem to work as myProp is undefined on the new page as oppose to pageId which I can get like:

this.props.params.pageId;

Am I not supposed to be able to pass non-route related parameters with Link?

like image 881
user2915962 Avatar asked Oct 18 '22 15:10

user2915962


2 Answers

In the documentation for Link and also the source, there's no mention of it taking param. But I get what you're trying to do.

Instead of hard-coding routes, may I recommend using react-router's history function router.push(). Do something like this instead:

class Foo extends React.Component {
  ...
  const handleNewRoute = () => {
     let { pageId } = this.props.data
     let singleId = '1'
     this.context.router.push({    // use push
       pathname: `/single/${pageId}`,
       query: { singleId }
     })
  }

  render() {
     return (
         <button onLeftClick={this.handleNewRoute} />
     )
  }
}

By the way, in React/JSX, something like ...{{singleId: 1, myProp={this.props.data}}}... should be <Link...foobar={{singleId: 1, myProp: this.props.data}}>. The former syntax is wrong.

like image 146
zelcon Avatar answered Nov 03 '22 09:11

zelcon


I think the better way to get the additional data is an ajax.

But if you want your way to do this,I check the api of Link and I find a query property.

query:

An object of key:value pairs to be stringified.

so you can use this to pass a object of key:value to the next route,but this object will be stringified and passed though the url I think.I prefer an ajax for this.

like image 24
Winsky Wen Avatar answered Nov 03 '22 08:11

Winsky Wen