Home > Software design >  How to make Navigation work with Routes if they are in the different packages?
How to make Navigation work with Routes if they are in the different packages?

Time:09-29

I have some components in react App that I moved to a separate lerna package (apart from App.js and Routes.js) and it caused that my Navigation together with History stopped working). Any suggestion how to fix this separation that it work to Navigate to different URL?

Here are the files in that separate packages:

History.js:

 import { createBrowserHistory } from 'history';

 export default createBrowserHistory(); 

Navigation.js

 import history from '../utils/History';

  export default function Nav(loc, state) {
  history.push(loc, state);
  }

function in the class that I want t work with Nav import Nav from '../Navigation';

     class MyComponent extends Component {
     constructor(props) {
     super(props);
     this.handleClick = this.handleClick.bind(this);
     }

    handleClick(c) {  
    Nav('/main/'   c.name;)
    }

And here is Routes from another package(simplified)

  import { MyComponent } from '@MyComponents';
  import { Switch, Route, Redirect } from 'react-router-dom';

  const Routes = () => (
  <Switch>
  <Route
  exact
  path='/'
  render={props => (
      <MyComponent
        {...props}      
      />bla...bla..))

I get my URL in the browser http://localhost:3000/main/componentname But it doesn't redirect to the URL, only if I refresh

Any suggestions how I can make Navigation work if Routes is in one component and Navigation History in another? Callback functions a bit difficult to implement if the Application becomes too complicated. Is there any other ways to fix it?

CodePudding user response:

I think you don't need Navigation.js & History.js you just change your YourComponent with:

YourComponent

class MyComponent extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}

handleClick(c) {
  
this.props.history.push(`/main/${c.name}`)
}

To understand how to implement this, you need to know that when a component is rendered by the router, three properties are passed as parameters:

  1. match
  2. location
  3. history

in this case we use history in this.props.history to push our path into /main/${c.name}

  • Related