Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access history object outside <Route /> in React Router v4

I have this following code:

import {
  BrowserRouter as Router,
  Route,
  Link
} from 'react-router-dom'


const Routes = () => (
  <Router basename="/blog">
    <div>
      <Header />
      <Route exact path="/" component={Main}/>
      <Route path="/article/:id" component={ArticleView}/>
    </div>
  </Router>
)

I can access history or match via props in the Main and ArticleView component. But I cannot access it in the <Header />. Is there a way to get the history object in the Header component?

like image 230
Tahnik Mustasin Avatar asked Mar 04 '17 10:03

Tahnik Mustasin


People also ask

How do you access history outside the react component?

We would obviously want some additional logic in there, but the point is that we can access the history object through props , even though no props were passed to Login , and use history. push to push a new entry onto the history stack.

How do I find history on react router v4?

Show activity on this post. import {useHistory } from "react-router-dom"; const TheContext = React. createContext(null); const App = () => { const history = useHistory(); <TheContext.

How do you use .push history in react?

Use the withRouter high-order component Instead you should use the withRouter high order component, and wrap that to the component that will push to history. For example: import React from "react"; import { withRouter } from "react-router-dom"; class MyComponent extends React. Component { ...


1 Answers

You can use the withRouter HOC for this.

Where your Header component is defined, wrapping the export in a withRouter invocation like below will give your Header component access to match, location, and history

import {withRouter} from 'react-router'

class Header extends Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }
  render () {
    const { match, location, history } = this.props

    return <h2>The Header</h2>
  }
}

export default withRouter(Header)
like image 195
Tyler McGinnis Avatar answered Sep 21 '22 23:09

Tyler McGinnis