1

I wonder how can I pass clicked item id to route path in React?

Here is my parent component

export default class ParentComponent extends Component {
  state = {
    data: null
  };
  render() {
    return (
      <section>
        <Row>
          <ul>
              <li>....<li>
              ....
          <ul>
        </Row>
        <Row>
          <ChildComponent rowData={this.state.data} />
        </Row>
      </section>
    );
  }
}

I have a list element when I click to some of li element I get the id of this element. So far, everything is ok.

I wonder how and where I can pass the childComponent this item id like path parameter dynamically.

My id in this.state.data.id, and I want to create and pass this id to route of component

url will be like: details/id

So on click to li element route will go to child component and child component will have id of clicked item.

I'm using react-router

my route paths in my app.js:

<Switch>
    <Route path="/login" /> 
    <Route exact path="/callback" />
    <Route  path="/about" component={About} /> 
</Switch>
1
  • tried Link? Commented May 19, 2019 at 17:33

1 Answer 1

2

You can use url params. kindly check below url https://reacttraining.com/react-router/web/example/url-params

<Switch>
    <Route path="/login" /> 
    <Route exact path="/callback" />
    <Route  path="/about" component={About} /> 
    <Route  path="/details/:id" component={DynamicComp} />
</Switch>

var DynamicComp = ({match})=>({<div>{match.params.id}</div>})
Sign up to request clarification or add additional context in comments.

9 Comments

I'll try but i'm confused. where i will link to my component? in my click function? where click working on list element click
On li click <li onClick={e=>this.context.router.transitionTo('/details/'+id)}> Home</li> or <li> <Link to={'/details/'+id}>Home</Link></li>
i'm getting TypeError: Cannot read property 'transitionTo' of undefined when i try to add this in my click function : onClick: (e, handleOriginal) => { this.context.router.transitionTo('/details/'+id) } i also don't understand where i will put it ? var DynamicComp = ({match})=>({<div>{match.params.id}</div>})
I can't. i need to be done it in onclick function only.
try onClick={() => history.push('/details/'+id)}
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.