Skip to content

Commit 2e115b8

Browse files
author
Dustin Masters
committed
Link to context page
1 parent 9277f06 commit 2e115b8

File tree

1 file changed

+13
-4
lines changed

1 file changed

+13
-4
lines changed

content/docs/reference-react-component.md

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -136,18 +136,18 @@ render() {
136136
### `constructor()`
137137

138138
```javascript
139-
constructor(props, context)
139+
constructor(props)
140140
```
141141

142-
The constructor for a React component is called before it is mounted. When implementing the constructor for a `React.Component` subclass, you should call `super(props)` before any other statement. Otherwise, `this.props` will be undefined in the constructor, which can lead to bugs. Optionally, if you need access to context in your component, call `super(props, context)`.
142+
The constructor for a React component is called before it is mounted. When implementing the constructor for a `React.Component` subclass, you should call `super(props)` before any other statement. Otherwise, `this.props` will be undefined in the constructor, which can lead to bugs.
143143

144144
The constructor is the right place to initialize state. If you don't initialize state and you don't bind methods, you don't need to implement a constructor for your React component.
145145

146146
It's okay to initialize state based on props. This effectively "forks" the props and sets the state with the initial props. Here's an example of a valid `React.Component` subclass constructor:
147147

148148
```js
149-
constructor(props, context) {
150-
super(props, context);
149+
constructor(props) {
150+
super(props);
151151
this.state = {
152152
color: props.initialColor
153153
};
@@ -158,6 +158,15 @@ Beware of this pattern, as state won't be up-to-date with any props update. Inst
158158

159159
If you "fork" props by using them for state, you might also want to implement [`componentWillReceiveProps(nextProps)`](#componentwillreceiveprops) to keep the state up-to-date with them. But lifting state up is often easier and less bug-prone.
160160

161+
Some libraries, such as React Router, may depend on [context](/docs/context.html) being available. If you implement a constructor and need context, make sure to call `super(props, context)`.
162+
163+
```js
164+
constructor(props, context) {
165+
super(props, context);
166+
// other component initialization logic
167+
}
168+
```
169+
161170
* * *
162171

163172
### `componentWillMount()`

0 commit comments

Comments
 (0)