Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get route parameters in React [duplicate]

<Route path="chats/:id" element={<Chat />} />
import React from "react";

export default class Chat extends React.Component {
  render() {
    return (
      <>
        {this.props.match.params.id}
      </>
    )
  }
}

If I use this, I only get a white site and the following error:

Chat.js:6 Uncaught TypeError: Cannot read properties of undefined (reading 'params')
    at Chat.render (Chat.js:6:1)
    at finishClassComponent (react-dom.development.js:20487:1)
    at updateClassComponent (react-dom.development.js:20433:1)
    at beginWork (react-dom.development.js:22366:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4157:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4206:1)
    at invokeGuardedCallback (react-dom.development.js:4270:1)
    at beginWork$1 (react-dom.development.js:27243:1)
    at performUnitOfWork (react-dom.development.js:26392:1)
    at workLoopSync (react-dom.development.js:26303:1)

How can I get this to work? No tutorial or googling worked.

(I use react-router-dom v6)

like image 251
Jak2k Avatar asked May 18 '26 12:05

Jak2k


2 Answers

I'd recommend using the useParams hook for this use case. You'd have to use a functional component though. It would end up looking like this:

import React from 'react';
import { useParams } from 'react-router';

export default function Chat() {
  const params= useParams()

  return <>{params.id}</> 
}
like image 114
Barry Michael Doyle Avatar answered May 20 '26 03:05

Barry Michael Doyle


react-router@v6 docs provide a wrapper

// withRouter.js
import {
  useLocation,
  useNavigate,
  useParams,
} from "react-router-dom";

function withRouter(Component) {
  function ComponentWithRouterProp(props) {
    let location = useLocation();
    let navigate = useNavigate();
    let params = useParams();
    return (
      <Component
        {...props}
        router={{ location, navigate, params }}
      />
    );
  }

  return ComponentWithRouterProp;
}
export default withRouter

Then just use it

import React from "react";
import withRouter from './withRouter';

export default withRouter(class Chat extends React.Component {
  render() {

    return (
      <>
        {this.props.router.params.id}
      </>
    )
  }
})
like image 36
Levaya Pochta Avatar answered May 20 '26 03:05

Levaya Pochta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!