Improve uncontrolled form components documentation
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 11.8k
- Forks
- 7.9k
- Avg merge
- 1d 11h
- Merged PRs (30d)
- 11
Description
Referring to Uncontrolled Components I think there are some pitfalls to be documented when using them.
Rendering uncontrolled components correctly
In contrast to controlled components, uncontrolled components using
defaultValue,defaultCheckedshould not be rendered until the default is present, respectively<select>should not be rendered until the default and the<option>children are present, because the functionality of thedefaultValueordefaultCheckedis only given after mounting, not on updating.
Not being rendered can be achieved in two different ways:
- simply don't render it e.g.
return null - force rerender with changing
keyon it
If you strictly don't want partial results in your form use "B", else "C" would work.
// A)
// bad
class UncontrolledMotd extends React.Component {
state = {
text: null
};
async componentDidMount() {
const res = await fetch('/motd');
const text = await res.text();
this.setState({text});
}
render() {
// bad default
return (
<input type="text" defaultValue={this.state.text} />
);
}
}
// B)
// better: no render, no placeholder
class UncontrolledMotd extends React.Component {
state = {
loaded: false,
text: null
};
async componentDidMount() {
const res = await fetch('/motd');
const text = await res.text();
this.setState({loaded: true, text});
}
render() {
if (!this.state.loaded) {
return null;
}
return (
<input type="text" defaultValue={this.state.text} />
);
}
}
// C)
// better: placeholder, using key
class UncontrolledMotd extends React.Component {
state = {
loaded: false,
text: null
};
async componentDidMount() {
const res = await fetch('/motd');
const text = await res.text();
this.setState({loaded: true, text});
}
render() {
return (
<input key={!this.state.loaded ? 'preview' : 'final'} type="text" defaultValue={this.state.text} />
);
}
}
Did not test code above, but the idea in my current project and it works.
What do you think?
Regards Philipp
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reviewing the linked Uncontrolled Components documentation and the proposed examples in this issue. Verify the uncontrolled-component behavior and determine how the pitfalls should fit into the documentation; done means the relevant guidance and tested examples are incorporated clearly.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, react
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100