Search code examples
reactjsreact-props

React Cannot destructure property 'params' of 'this.props.match' as it is undefined


I have a route set up to render the details for an individual item but its throwing an error saying 'this.props.match' is undefined. Hence cant deconstruct

Here is my code snippet

class ProfilesSinglePage extends Component {
    constructor (props) {
        super (props)

        this.state={
            details:''
        };
    }
    render(){
        console.log(this.props);
        const {params} = this.props.match;
        return (
            <React.Fragment>
                <h1>Profiles Details for id {params.id}</h1>
            </React.Fragment>
        );
    };
    componentDidMount(){
        console.log(this.props.match.params.id);
        axios.get(`${Profiles}/${this.props.match.params.id}`)
        .then((res) => {
            this.setState({details:res.data})
        });
    };
};

Here is how the route looks like

      <Routes>
        <Route path="/profiles" exact element={<ProfilesAllPage/>}/>
        <Route path="/profile-details/:id" exact element={<ProfileSinglePage/>}/>
      </Routes>


Solution

  • you are using react v6 version hence to get access to params you need to import useParams from react-router-dom and then create a hook to access the URL parameters.

    for a better understanding visit- https://www.codingdeft.com/posts/react-get-query-and-url-parameters/#reading-url-parameters