Reputation: 23
I want to get params in my react class
I got file index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Button } from 'reactstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import { App, addPost, Child } from './components/App';
import { Switch , Route, BrowserRouter } from 'react-router-dom'
ReactDOM.render((
<BrowserRouter>
<Switch>
<Route exact path="/" component={App} />
<Route path="/dodajpost" component={addPost} />
<Route exact path="/:id" component={App} /> // this one
</Switch>
</BrowserRouter>
), document.getElementById('root'));
and now in my class i want to get the param ":id" and send it to server, but i don't know how to get it
export default class Post extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
};
}
componentDidMount () {
const { handle } = this.props.match.params
console.log(handle) // undefined
}
How can I get in componentDidMount
the params from route?
I tried many things and none working
Upvotes: 2
Views: 85
Reputation: 20765
As your Route
has param name as id
,
<Route exact path="/:id" component={App} />
Instead of this,
const { handle } = this.props.match.params
you should do this,
const { id } = this.props.match.params
console.log(id)
Note: You have 2 Route's
for App component. So when you are already in App component and try to navigate to path="/:id"
you will not get id
value, for that you may need componentDidUpdate
method.
componentDidUpdate () {
const { id } = this.props.match.params
console.log(id)
}
Or you may have a typo here, <Route exact path="/:id" component={App} />
, instead of App
as component you might have Child
(Post) component <Route exact path="/:id" component={Child} />
Upvotes: 3