Params from React Router with class components and typescript [duplicate]
Asked Answered
F

1

0

I have an application, that uses the class component syntax to create all components so far. With these package versions:

"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router": "^6.3.0",
"react-router-dom": "^6.3.0",
"react-scripts": "5.0.1",

I am trying to get my route parameters to my components. So I started with:

<Routes>
  <Route path="/Login" element={<Login authSuccessCallback={() => <Navigate to="/" />} />}></Route>
  <Route path="/EmailVerify/:id" element={<VerifyEmail />}></Route>
  <Route path="*" element={UserManager.IsLoggedIn() ? <></> : <Navigate to="/Login" />}></Route>
</Routes>

I alredy tried to:

  • extend my props with: RouteComponentProps<VerifyEmailRouteParams>
  • private id = useParams<VerifyEmailRouteParams>();
  • private params = useParams<{id:string}>();
  • just read from the params property in my props this.props.params.id (don't know why I'd expected this to work)
  • <Route path="/Contacts/VerifyEmailAddress/:id" render={(params) => <VerifyEmail {...params}></VerifyEmail>}>

I already found a lot on the web like:

I checked my props object with the debugger: enter image description here I also tried to use the render prop in the route, which is also undefined.

Is it the wrong approach to use class components, typescript or react-router together? Do I miss a library or type imports? (expected react comes with all needed types) Maybe a version mismatch? The router without parameters is working like a charme, but as soon I try to read parameters it will not compile anymore or have runtime issues.

Fungi answered 27/7, 2022 at 14:32 Comment(5)
is it possible for you to provide sandbox, or the code of your class component?Bravo
It is not compiling, because jsx not resolvable: codesandbox.io/s/react-typescript-forked-o7lo3j?file=/src/… but my code is quite similar to this.Fungi
You can not use hooks inside a class componentBravo
@AbhishekKumarPandey what is the right way to do it in a class component?Fungi
Can you please check it inside browser console, you must be getting props value in console, browser is showing props is empty may be because interface was not there for your props.Bravo
B
0

Since you are trying to use hooks inside a class component which is not recommended. you can not use useParams inside a class component

you can try something like this

componentDidMount(){
  const id = this.props.match.params
  console.log({id}) // return all the params object
 }
Bravo answered 27/7, 2022 at 16:36 Comment(2)
I know that it is not allowed to use the hooks in class components. I just thought I try it since I had no other way to get it to work. match isn't defined in props. :(Fungi
There are also not any route props in RRDv6, so this.props.match is undefined and an error will be thrown when attempting to access this.props.match.params.Cano

© 2022 - 2024 — McMap. All rights reserved.