1

I need help to fix this error with the best way I don't want to recall component inside withRouter with props

import { useNavigate } from 'react-router-dom'
import { Outlet } from 'react-router-dom'

class App {
  componentDidMount(): void {
    const navigate = useNavigate()
    navigate('/phone')
  }


  render(): React.ReactNode {
    return (
      <div className='App'>
         <Outlet />
      </div>
    )
  }
}

export default App

Error when use navigate

I try to navigate between two class components and I want to use animaiton between two classes via navigation

I search on the best to solve this error

  • Sure, `react-router-dom` can render components that are Class components. That's not the issue here though. React Class components cannot use React hooks; React hooks can only be called from React Function components or custom React hooks. Are you just trying to access the `navigate` function in a Class component? Do either of [this](/a/64566486/8690857) or [this](/a/69902006/8690857) help answer your question? – Drew Reese Oct 28 '22 at 18:34
  • FWIW I think I understand your question about "compatibility" now after another reading. In this sense, no, RRD isn't able to support Class components because they can't use React hooks. Creating a custom `withRouter` HOC or using the RRD hooks and passing props is the only way to access the `navigate` function in a Class component. There are likely dozens of answers on SO covering this, or you can read the official docs [What happened to withRouter? I need it!](https://reactrouter.com/en/main/start/faq#what-happened-to-withrouter-i-need-it). – Drew Reese Oct 28 '22 at 18:58
  • I have the same error – Faceless Void Oct 28 '22 at 19:02
  • Does `App` need to be a Class component? What does "I have the same error" mean? Did you try something *other than* the code in your question? – Drew Reese Oct 28 '22 at 19:05
  • Yes, the App needs to be a Class component. No, I didn't try something other than the code in my question. I always focus on Object Oriented principles when I use class and I prefer share class Example: export class App extends BaseClass {} – Faceless Void Oct 28 '22 at 19:24
  • 1
    I can tell you straight up from experience... OOP ***does not work well at all with React***. You'll be much better off just throwing OOP principles out the window and just learning how React wants you to use it. Class components are all but deprecated from a technical standpoint, React has made it clear that React functions and hooks are the future of `react`. You can read more about [Composition vs Inheritance](https://reactjs.org/docs/composition-vs-inheritance.html) if you like. – Drew Reese Oct 28 '22 at 19:26
  • Hahaha! Thank you. I read it before asking my question. – Faceless Void Oct 28 '22 at 19:34

0 Answers0