1
votes

I'm using react-router's <Link /> so that when a user clicks the link, myComponent is rendered.

My question is, how can I pass props into the myComponent from the Navigation component? This doesn't work, but I'm trying to pass a element.name prop from Navigation to myComponent.

class Navigation extends Component {
  const items = store.getState().items.map((element, index) =>
    <Link to={element.id} name={element.name}> element.id </Link>
  )

  render() {
    return (
      {items}
    )
  }
}

Here's the route setup & component setup:

<Route path=":id" component={myComponent} />

// I'd like to pass in props to be used here from the Navigation component, for example, a name prop passed through <Link />

class myCompnent extends Component {
  render() {
    return (
      <div>
        <p> hello {this.props.name} </p>
      </div>
    )
  }
}
2

2 Answers

2
votes

react-router Link

I don't think there is a way to pass props from <Link> to the component, But using 'query' params of Link can pass something with the path, it will be add on the path as query like: ?name=jack&aa=bb

<Link to={element.id} query={{ name: element.name }}>{element.id}</Link>

and get it from this.props.location.query in component

componentDidMount: function () {
    var query = this.props.location.query;
    if ( query && query.name ) {
        this.setState({
            name: name
        });
    } 
}

// in render
<p> hello {this.state.name} </p>
0
votes

What you can do is pass the props by appending them to the Component link in Parent Component and get them using componentWillReceiveProps method in child component.

For Example :

Parent Component

<Link to {`element.id/{$element.name}`}>{element.id}</Link>

Child Component

componentWillReceiveProps(nextProps) {
    if (nextProps.value !== this.props.value) {
        console.log(this.props); //Here you can fetch the props which you have passed
    }
}