2
votes

I have a route setup like so:

<Route path={'/mycomponent'} exact component={MyComponent} />

and navigate to it using an ActiveLink component:

import * as React from 'react' import { Link } from 'react-router-dom'

export interface OwnProps {
  to        : string,
  pathname  : string,
  children  : React.ReactChild
}

const ActiveLink = (props: OwnProps) => {

  const { pathname, to, children } = props

  if (pathname === to) {
    return <span className={ 'active-link active' }>{ children }</span>
  } else {
    return <Link className={ 'active-link in-active' } to={ to ? to : '/' }>{ children }</Link>
  }
}

export default ActiveLink

I would like to find a way to pass data to 'MyComponent' (preferably in the props), something that is the equivalent of '/MyComponent?aparam=hello&anotherparam=32'

2
Btw, in case of you component is not a direct descendant of some Route, when you can wrap it with withRouter() and same props passed to it - Daniel Khoroshko

2 Answers

3
votes

Let say you have below route that you explained.

<Route path={'/mycomponent'} exact component={MyComponent} />

Now if you redirect on route let's say

MyComponent?aparam=hello&anotherparam=32

So in you MyComponent class you can get that both parameters like below

let aparam = this.props.match.params.aparam;
let anotherparam = this.props.match.params.anotherparam;

Hope this will help, if not then please elaborate more about your question Thnaks :)

3
votes

It is a good practice to define passing params in route, like this.

<Route path={'/mycomponent/:aparam/:anotherparam'} exact component={MyComponent} />

Then you could navigate to MyComponent and pass params in this way:

<Link to="mycomponent/hello/32">{children}</Link>

Finally aparam and anotherparam will be avaliable in MyComponent via prop values

this.props.match.params.aparam;
this.props.match.params.anotherparam;