Skip to content

Commit a48fdd9

Browse files
committed
Merge pull request #3351 from reactjs/clarify-contextTypes
Clarify contextTypes docs
2 parents a11a10b + 2bd818b commit a48fdd9

File tree

1 file changed

+28
-14
lines changed

1 file changed

+28
-14
lines changed

docs/API.md

Lines changed: 28 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -171,44 +171,58 @@ It also provides a `router` object on [context](https://facebook.github.io/react
171171

172172
Contains data and methods relevant to routing. Most useful for imperatively transitioning around the application.
173173

174-
To use it, you must signal to React that you need it by declaring your use of it in your component:
174+
To use it, you must signal to React that you need it by declaring your use of it in your component via `contextTypes`:
175175

176176
```js
177177
var MyComponent = React.createClass({
178178
contextTypes: {
179-
router: Router.PropTypes.router
179+
router: routerShape.isRequired
180180
},
181+
181182
render: function() {
182-
// here, you can use `this.context.router`
183+
// Here, you can use this.context.router.
183184
}
184-
});
185+
})
186+
```
185187

188+
To use `context.router` on a component declared as an ES2015 class, define `contextTypes` as a static property of the class:
189+
190+
```js
191+
class MyComponent extends React.Component {
192+
render() {
193+
// Here, you can use this.context.router.
194+
}
195+
}
196+
197+
MyComponent.contextTypes = {
198+
router: routerShape.isRequired
199+
}
186200
```
187201

188-
Using `context.router` in combination with ES6 classes requires a different pattern (note the use of the `static` keyword):
202+
If you are using the class properties proposal, you can instead write:
189203

190204
```js
191205
class MyComponent extends React.Component {
192206
static contextTypes = {
193-
router: Router.PropTypes.router
207+
router: routerShape.isRequired
194208
}
195209

196-
render: function() {
197-
// here, you can use `this.context.router`
210+
render() {
211+
// Here, you can use this.context.router.
198212
}
199-
});
200-
213+
}
201214
```
202215

203-
Finally, you can use `context.router` with
204-
[stateless function components](https://facebook.github.io/react/docs/reusable-components.html#stateless-functions):
216+
To use `context.router` with
217+
[stateless function components](https://facebook.github.io/react/docs/reusable-components.html#stateless-functions), declare `contextTypes` as a static property of the component function:
205218

206219
```js
207220
function MyComponent(props, context) {
208-
// here, you can use `context.router`
221+
// Here, you can use context.router.
209222
}
223+
210224
MyComponent.contextTypes = {
211-
router: Router.PropTypes.router
225+
router: routerShape.isRequired
212226
}
213227
```
214228

0 commit comments

Comments
 (0)