Our withPokemon
HOC is mostly reusable. But it displays that static
loading...
message.
Letβs make that replaceable.
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
)
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.
Use the workspace below and explore defaultProps
.
static defaultProps
to todayβs syntax and back again.renderLoading
to use a render prop. What changes in
render()
?Loading
and use it in
defaultProps
. What changes in render()
?