Day 22: A sensible default
Our withPokemon HOC is mostly reusable. But it displays that static
loading... message.
Let’s make that replaceable.
Components over configuration
The defaultProps API is one of my favorites. Use it to provide sensible
defaults for your components.
For withPokemon, we should always indicate that the component is doing work.
But we should make make the message configurable.
We know that props can be components. So lets put <div>loading...</div> in
defaultProps.
class FetchPokemon extends React.Component { ... }
FetchPokemon.defaultProps = {
renderLoading: <div>loading...</div>
}
(Yes, this works with component functions and classes alike.)
Now we update render() and anyone on the team can use any loading component
they want.
return this.state.character ? (
<Component character={this.state.character} />
) : (
this.props.renderLoading
)
Future syntax
CodeSandbox and
create-react-app
provide syntactic sugar for defaultProps.
class FetchPokemon extends React.Component {
static defaultProps = {
renderLoading: <div>loading...</div>,
}
}
It reduces redundant typing but only for class components.
Tinker with it
Use the workspace below and explore defaultProps.
- Change
static defaultPropsto today’s syntax and back again. - Change
renderLoadingto use a render prop. What changes inrender()? - Create a new functional component named
Loadingand use it indefaultProps. What changes inrender()?