2

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?

Dylan
  • 1,121
  • 1
  • 13
  • 28

2 Answers2

1

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>
);
Tholle
  • 108,070
  • 19
  • 198
  • 189
  • I use `import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';` there and it didn't work, then I remove the `BrowserRouter as` at my code it worked, and still, I confused why it didn't worked at the BrowserRouter – Dylan Nov 02 '18 at 01:54
  • 1
    @MarkDylanBMercado `BrowserRouter` creates a `history` of its own, and doesn't take a `history` prop. Only `Router` can be passed a `history` prop. – Tholle Nov 02 '18 at 08:22
0

Why not wrapper header component with “withRouter”?

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md

Reactify
  • 29
  • 1
  • 5