Edwin
Edwin

Reputation: 69

How can i pass my props when using react-router

I have a react router Link that sends me to a component called New

 <Link to="/New"> New  </Link>

Here is the routing configuration for New

 <Route path="/New" component={New}></Route>

Now my question is this, how can I pass props to the New Item Component.

Normally I would do this <New Onchange={this.handleChange} onsubmit={this.handleSubmit}/>

Thanks in advance for your assistance.

Upvotes: -1

Views: 128

Answers (3)

maten
maten

Reputation: 586

If you use React Router v5.1+, you can actually use the Route component like this:

<Route path="/path">
    <Component {whatever props you want to pass} />
</Route>

To pass props through the Link component:

<Link to={{
  pathname: '/new',
  state: {
    propsToPass: 'whatever'
  }
}}>New</Link>

Then in your New component:

import { useLocation } from 'react-router-dom'

const location = useLocation();

console.log(location.state.propsToPass) // logs 'whatever'

Upvotes: 1

Aditya Patnaik
Aditya Patnaik

Reputation: 1776

You can do that using render with a callback.

<Route path="/New" render={(props) => <New text="Hello, " {...props} />} />

Hope this is what you are looking for. Hope this helps!

Upvotes: 1

Artem
Artem

Reputation: 33

You can wrap the component into an arrow function

<Route path="/New" component={(props) => <New props={props}/>}></Route>

Upvotes: 1

Related Questions