mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 07:08:01 +00:00
Add Use withRouter To Pass Down React-Router History as a react til
This commit is contained in:
@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
|
|||||||
For a steady stream of TILs from a variety of rocketeers, checkout
|
For a steady stream of TILs from a variety of rocketeers, checkout
|
||||||
[til.hashrocket.com](https://til.hashrocket.com/).
|
[til.hashrocket.com](https://til.hashrocket.com/).
|
||||||
|
|
||||||
_628 TILs and counting..._
|
_629 TILs and counting..._
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -445,6 +445,7 @@ _628 TILs and counting..._
|
|||||||
- [Read Only Input Elements](react/read-only-input-elements.md)
|
- [Read Only Input Elements](react/read-only-input-elements.md)
|
||||||
- [Rendering Multiple Nodes With Fragments](react/rendering-multiple-nodes-with-fragments.md)
|
- [Rendering Multiple Nodes With Fragments](react/rendering-multiple-nodes-with-fragments.md)
|
||||||
- [Use A Ref To Autofocus An Input](react/use-a-ref-to-autofocus-an-input.md)
|
- [Use A Ref To Autofocus An Input](react/use-a-ref-to-autofocus-an-input.md)
|
||||||
|
- [Use withRouter To Pass Down React-Router History](react/use-withrouter-to-pass-down-react-router-history.md)
|
||||||
- [Visually Select A React Element For Inspection](react/visually-select-a-react-element-for-inspection.md)
|
- [Visually Select A React Element For Inspection](react/visually-select-a-react-element-for-inspection.md)
|
||||||
|
|
||||||
### ReasonML
|
### ReasonML
|
||||||
|
|||||||
28
react/use-withrouter-to-pass-down-react-router-history.md
Normal file
28
react/use-withrouter-to-pass-down-react-router-history.md
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
# Use withRouter To Pass Down React-Router History
|
||||||
|
|
||||||
|
A standard way to navigate with
|
||||||
|
[react-router](https://github.com/ReactTraining/react-router) besides using
|
||||||
|
the `Link` component is to call `history.push`. Components that are directly
|
||||||
|
rendered by a `Route` will have access to this and other router props. But
|
||||||
|
what about other components?
|
||||||
|
|
||||||
|
The `withRouter` HOC gives us direct access to a `history` prop.
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
import React from 'react';
|
||||||
|
import { withRouter } from 'react-router';
|
||||||
|
|
||||||
|
const SpecialButton = withRouter(({ history, path, text }) => {
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
onClick={() => { history.push(path); }}
|
||||||
|
>
|
||||||
|
{text}
|
||||||
|
</Button>
|
||||||
|
)
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
This special button component is given the `history` prop via the
|
||||||
|
`withRouter` HOC along with any props that we directly pass it. With that
|
||||||
|
we are able to directly invoke a route change using `history.push()`.
|
||||||
Reference in New Issue
Block a user