Components can be configured upon instantiation by passing properties to the
constructor - these properties are called
props may be accessed from within the component's methods as
this.props, in order to alter how the component is rendered and/or how it behaves. However,
props must not be altered from within the component's methods.
A parent element may alter a child element's
props at any time. The child element will generally re-render itself to reflect its new configuration parameters. A child component may decide not to re-render itself even though its configuration has changed, as determined by
shouldComponentUpdate() (more on this in the Component Lifecycle API section).
You may set default values for
props by assigning an object to the static class property
defaultProps, where the keys are the prop names and the values are the default prop values.
You may also define the types of
props that a component expects by assigning an object to the static class property
propTypes, where the keys are the prop names and the values are prop types, from the
npm module (formerly
React.PropTypes). We won't be using
PropTypes in our examples, but they're very useful once you start working with larger and more complex codebases.
Components may maintain their state internally within the object
this.state may be accessed from within component methods. Unlike
props, parent elements may not access a child's
state, as it is intended to manage the child's internal state rather than external configuration.
Note that you should never directly assign to a specific key within the
state object, e.g.
this.state.foo = 'bar', but instead use the method
Components may update their
state by passing an object to the method
this.setState(). Any keys in the object passed to the method will be merged into (and override any existing keys in)
The following example includes a
Counter component that maintains the elapsed time internally as
App component renders the
Counter component with two
App can easily render several
Counter components with different sizes and colors.