Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions wiki/react-router.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,8 @@ export const getRouterLinkProps = to => {

## react-router 5.x

### react-router 5.0

The React Context handling has changed in in 5.0 and we can't rely on it anymore. A solution is to create
an `extractRouter` HOC that will intercept the router and send it to your custom handler.

Expand Down Expand Up @@ -292,6 +294,66 @@ ReactDOM.render(
)
```

### react-router 5.1

In react-router 5.1, we can fully capitalize in the React Hooks utility, in this case, `useHistory`. Using this, we do not need other HOC wrapper files and global router variable. We just need to create the file below, and then use it anywhere by importing `EuiCustomLink`. There is an example repository for this: https://github.com/Imballinst/elastic-react-router-hooks.

```jsx
// File name: "EuiCustomLink.js".
import React from 'react';
import { EuiLink } from '@elastic/eui';
import { useHistory } from 'react-router';

// Most of the content of this files are from https://github.com/elastic/eui/pull/1976.
const isModifiedEvent = (event) =>
!!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);

const isLeftClickEvent = (event) => event.button === 0;

export default function EuiCustomLink({ to, ...props }) {
// This is the key!
const history = useHistory();

function onClick(event) {
if (event.defaultPrevented) {
return;
}

// If target prop is set (e.g. to "_blank"), let browser handle link.
if (event.target.getAttribute('target')) {
return;
}

if (isModifiedEvent(event) || !isLeftClickEvent(event)) {
return;
}

// Prevent regular link behavior, which causes a browser refresh.
event.preventDefault();

// Push the route to the history.
history.push(to);
}

return <EuiLink {...props} href={to} onClick={onClick} />;
}
```

```jsx
// App is your app's root component.
class App extends Component {
...
}

// <App> *must* be a child of <Router> because <App> depends on the context provided by <Router>
ReactDOM.render(
<Router>
<App />,
</Router>,
appRoot
)
```


## Techniques we don't recommend

Expand Down