React Component API
ReactJS goes through a development process. Initially, the components are written based on the old Javascript syntax. Until 0.14, ReactJS version, it was transfered to use the Javascript according to the ES6 standard. Many old Component APIs are deprecated or removed to conform to the new standard. In this lesson, I just introduce the useful Component APIs and is suitable for Javascript ES6.
- setState()
- forceUpdate
- ReactDOM.findDOMNode()
setState
setState(object nextState[, function callback])
Merges nextState with the current state. This is the primary method you use to trigger UI updates from event handlers and server request callbacks. In addition, you can supply an optional callback function that is executed once setState
is completed and the component is re-rendered.
Notes:
NEVER mutate this.state
directly, as calling setState()
afterwards may replace the mutation you made. Treat this.state
as if it were immutable.
setState()
does not immediately mutate this.state
but creates a pending state transition. Accessing this.state
after calling this method can potentially return the existing value.
There is no guarantee of synchronous operation of calls to setState
and calls may be batched for performance gains.
setState()
will always trigger a re-render unless conditional rendering logic is implemented in shouldComponentUpdate()
. If mutable objects are being used and the logic cannot be implemented in shouldComponentUpdate()
, calling setState()
only when the new state differs from the previous state will avoid unnecessary re-renders.
import React from 'react';
class App extends React.Component {
constructor() {
super();
this.state = {
data: []
}
this.setStateHandler = this.setStateHandler.bind(this);
};
setStateHandler() {
var item = "setState..."
var myArray = this.state.data.slice();
myArray.push(item);
this.setState({data: myArray})
};
render() {
return (
<div>
<button onClick = {this.setStateHandler}>SET STATE</button>
<h4>State Array: {this.state.data}</h4>
</div>
);
}
}
export default App;
We started with an empty array. Every time we click the button, the state will be updated. If we click five times, we will get the following output.
replaceState
replaceState(object nextState[, function callback])
Like setState()
but deletes any pre-existing state keys that are not in nextState.
forceUpdate()
forceUpdate([function callback])
If your render()
method reads from something other than this.props
or this.state
, you’ll need to tell React when it needs to re-run render()
by calling forceUpdate()
. You’ll also need to call forceUpdate()
if you mutate this.state
directly.
Calling forceUpdate()
will cause render()
to be called on the component and its children, but React will still only update the DOM if the markup changes.
Normally you should try to avoid all uses of forceUpdate()
and only read from this.props
and this.state
in render()
. This makes your application much simpler and more efficient.
import React from 'react';
class App extends React.Component {
constructor() {
super();
this.forceUpdateHandler = this.forceUpdateHandler.bind(this);
};
forceUpdateHandler() {
this.forceUpdate();
};
render() {
return (
<div>
<button onClick = {this.forceUpdateHandler}>FORCE UPDATE</button>
<h4>Random number: {Math.random()}</h4>
</div>
);
}
}
export default App;
getDOMNode
DOMElement getDOMNode()
If this component has been mounted into the DOM, this returns the corresponding native browser DOM element. This method is useful for reading values out of the DOM, such as form field values and performing DOM measurements. When render
returns null
or false
, this.getDOMNode()
returns null
.
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor() {
super();
this.findDomNodeHandler = this.findDomNodeHandler.bind(this);
};
findDomNodeHandler() {
var myDiv = document.getElementById('myDiv');
ReactDOM.findDOMNode(myDiv).style.color = 'green';
}
render() {
return (
<div>
<button onClick = {this.findDomNodeHandler}>FIND DOME NODE</button>
<div id = "myDiv">NODE</div>
</div>
);
}
}
export default App;
The color of myDiv element changes to green, once the button is clicked.
isMounted()
bool isMounted()
isMounted()
returns true if the component is rendered into the DOM, false otherwise. You can use this method to guard asynchronous calls to setState()
or forceUpdate()
.
transferPropsTo
ReactComponent transferPropsTo(ReactComponent targetComponent)
Transfer properties from this component to a target component that have not already been set on the target component. After the props are updated, targetComponent
is returned as a convenience. This function is useful when creating simple HTML-like components:
var Avatar = React.createClass({
render: function() {
return this.transferPropsTo(
<img src={"/avatars/" + this.props.userId + ".png"} userId={null} />
);
}
});
// <Avatar userId={17} width={200} height={200} />
Properties that are specified directly on the target component instance (such as src
and userId
in the above example) will not be overwritten by transferPropsTo
.
Note:
Use transferPropsTo
with caution; it encourages tight coupling and makes it easy to accidentally introduce implicit dependencies between components. When in doubt, it’s safer to explicitly copy the properties that you need onto the child component.
setProps
setProps(object nextProps[, function callback])
When you’re integrating with an external JavaScript application you may want to signal a change to a React component rendered with React.renderComponent()
.
Though calling React.renderComponent()
again on the same node is the preferred way to update a root-level component, you can also call setProps()
to change its properties and trigger a re-render. In addition, you can supply an optional callback function that is executed once setProps
is completed and the component is re-rendered.
Note:
When possible, the declarative approach of calling React.renderComponent()
again is preferred; it tends to make updates easier to reason about. (There’s no significant performance difference between the two approaches.)
This method can only be called on a root-level component. That is, it’s only available on the component passed directly to React.renderComponent()
and none of its children. If you’re inclined to use setProps()
on a child component, instead take advantage of reactive updates and pass the new prop to the child component when it’s created in render()
.
replaceProps
replaceProps(object nextProps[, function callback])
Like setProps()
but deletes any pre-existing props instead of merging the two objects.