reactjsreact-routerrouterreact-domnavigateurl

ReactJS Changing the route using a button that is rendering on other ReactDOM


I have two rendering ReactDOM at my index.js

ReactDOM.render(<Header />, document.getElementById('header'));
ReactDOM.render(<App />, document.getElementById('root'));

Now, inside my App.js I have three route

<Router>
    <Switch>
        <Route exact path = "/" component = { page1 }/>
        <Route path = "/page1" component = { page1 }/>
        <Route path = "/page2" component = { page2 }/>
    </Switch>
</Router>

Then in my Header.js file, I have a button that I want to do a job to navigate to another route or page

<button onClick={() => this.props.history.push('/page2')}> Next </button>

but the problem is I'm having an error saying that

TypeError: Cannot read property 'push' of undefined

I know that it's not in the react router so I can't use the link, but I don't know what should I must do,
The question is, how can I navigate from one route to another using a button that is rendering from another ReactDOM and not inside of the ReactDOM that I wanted to change the route with?


Solution

  • You can create the history object manually with the history library and export that from a separate module that you can give to your Router component and use in your Header component.

    Example

    // history.js
    import createHistory from 'history/createBrowserHistory';
    
    const history = createHistory();
    
    export default history;
    
    // App.js
    import history from './history';
    
    export default () => (
      <Router history={history}>
        <Switch>
          <Route exact path = "/" component = { page1 }/>
          <Route path = "/page1" component = { page1 }/>
          <Route path = "/page2" component = { page2 }/>
        </Switch>
      </Router>
    );
    
    // Header.js
    import history from './history';
    
    export default () => (
      <button onClick={() => history.push('/page2')}> Next </button>
    );