Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router with arguments?

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'

like image 731
meds Avatar asked Jan 27 '26 04:01

meds


2 Answers

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 :)

like image 144
Binit Ghetiya Avatar answered Jan 28 '26 18:01

Binit Ghetiya


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;
like image 33
Sasha Kos Avatar answered Jan 28 '26 20:01

Sasha Kos