Home > Software engineering >  withNavigation on class component with typescript
withNavigation on class component with typescript

Time:03-30

Please help me get this minimum-working example with withNavigation to work

https://codesandbox.io/s/withnavigation-not-working-lds560?file=/src/index.js

import React, {Component} from "react";
import {withNavigation, NavigationInjectedProps} from "react-navigation";

class App extends Component<NavigationInjectedProps> {
  render() {
    return <h1>Hello CodeSandbox</h1>;
  }
}

export default withNavigation(App);

CodePudding user response:

I found a little hacky-solution in which you create your own custom withNavigation. (I am still looking for a solution to make it work without having to create your own custom withNavigation function)

App.tsx

import React, {Component} from "react";
import {useNavigate, NavigateFunction} from "react-router-dom";

class App extends Component<{navigate: NavigateFunction, text: string}> {
  render() {
    return <button onClick={() => this.props.navigate("/c")}>
      We are at path: {this.props.text}, navigate to "/c"
    </button>;
      
  }
}

function withNavigation(Component: any): (props: any) => JSX.Element {
  return props => <Component {...props} navigate={useNavigate()} />;
}

export default withNavigation(App);

index.js

import * as ReactDOMClient from "react-dom/client";
import {Route, Routes, BrowserRouter } from "react-router-dom";

import App from "./App";

const rootElement = document.getElementById("root");
const root = ReactDOMClient.createRoot(rootElement);

root.render(
<BrowserRouter>
  <Routes>
    <Route path="/a" element={<App text={"a"}/>}/>
    <Route path="/b" element={<App text={"b"}/>}/>
  </Routes>
</BrowserRouter>
);

CodePudding user response:

You need to move your

import {withNavigation, NavigationInjectedProps} from "react-navigation"

to a separate file which you have to include in App and wrap in in <Navigation Container>.

See here

Update:

I’ve just seen that you are trying to work with react-navigation 4! This probably won’t work with my solution but considering that version 4^ is no longer maintained, you might think about updating to version 5^.

  • Related