Skip to content

Commit e845537

Browse files
authored
Merge pull request #7 from AryanJ-NYC/develop
Add React Router docs
2 parents 0327810 + 5609e60 commit e845537

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
---
2+
name: React Router
3+
route: /examples/react-router
4+
menu: Examples
5+
---
6+
7+
# React Router
8+
9+
## withRouter
10+
11+
To use a component injected with `withRouter` props, import and use `RouteComponentProps` ([declaration](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/index.d.ts#L71)) from `react-router`:
12+
13+
```typescript
14+
import { RouteComponentProps, withRouter } from 'react-router';
15+
16+
type SomeComponentProps = RouteComponentProps;
17+
18+
const SomeComponent: React.FC<SomeComponentProps> = ({ history }) => {
19+
const goHome = () => history.push('/home');
20+
21+
return <button onClick={goHome}>Go Home</button>;
22+
};
23+
24+
export default withRouter(SomeComponent);
25+
```
26+
27+
## URL Parameters
28+
29+
To type URL parameters, import and use `RouteComponentProps` ([declaration](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/index.d.ts#L71)) from `react-router`. Pass your parameter definitions as a type variable to `RouteComponentProps`:
30+
31+
```tsx
32+
// Router.tsx
33+
import { BrowserRouter, Route } from 'react-router-dom';
34+
35+
const Router = () => {
36+
return (
37+
<BrowserRouter>
38+
<Route exact path="/books/:id" component={Books} />
39+
</BrowserRouter>
40+
);
41+
};
42+
43+
// BookDetail.tsx
44+
import { RouteComponentProps, withRouter } from 'react-router';
45+
46+
type BookDetailParams = {
47+
id: string; // parameters will always be a string (even if they are numerical)
48+
};
49+
50+
type BookDetailProps = RouteComponentProps<BookDetailParams>;
51+
52+
const BookDetail: React.FC<> = ({ match }) => {
53+
return <div>Book ID: {match.params.id}</div>;
54+
};
55+
56+
export default withRouter(BookDetail);
57+
```

0 commit comments

Comments
 (0)