I have a route <Route path="post/:id" element={<PostByIdPage />} />
How can i get param id as props in react router dom v6?
Here is my PostByIdPage component :
import React, { Component } from 'react';
import OneSecret from '../OneSecret';
import getSecretsPublic from '../../../action/getSecretsPublic';
import { connect } from 'react-redux';
export class index extends Component {
constructor(props) {
super(props);
this.state = {
secretPublic: {
content: ''
}
}
let id = decodeURI(window.location.pathname.substring(6));
let params = {
id: id
}
this.props.getSecretsPublic(params)
.then(res =>{
if (res.type === 'ERROR_MESSAGE') {
return;
}
this.setState({secretPublic: res.payload.data[0]})
});
}
render() {
return (
<div>
<OneSecret element={this.state.secretPublic} key={this.state.secretPublic.id} />
</div>
)
}
}
export default connect(null, {getSecretsPublic})(index)
I'm using window.location.pathname and split to get param but i want to get params from props to re render() my component based in params
Little late to answer but you can achieve it easily. <this.props.match> will be available once you use {useParams} from react-router-dom but its a little tricky for class-based components. If using functional component, you have a choice of directly using {useParams} and props.match will be available. For Class-based components like your case, You can do this with High order component:
import { useParams } from 'react-router-dom';
export function withRouter(Children) {
return (props) => {
const match = { params: useParams() };
return <Children {...props} match={match} />
}
}
class PostByIdPage extends Component {
render() {
return (
<div className="App">
<h1>Page for {this.props.match.params.id}</h1>
</div>
);
}
}
export default withRouter(PostByIdPage);
Now in you classbased component, You can access id as:
this.props.match.params.id
No more Error for ' this.props.match is undefined'
i think its the same as before you can use useParams() like this:
let { id } = useParams();
update:
<Route path= "third/:id" element={Content}/>
this is my code to call to the component and this is the component:
class Content extends Component {
componentDidMount () {
console.log( this.props.match.params.id );
}
render() {
return (
<div className="App">
<h1>Third</h1>
</div>
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With