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?
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.
Show activity on this post. import {useHistory } from "react-router-dom"; const TheContext = React. createContext(null); const App = () => { const history = useHistory(); <TheContext.
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 { ...
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With