Conditionally controlled component with `value` and `defaultValue` properties
まだ誰も着手していません。
- 主要言語
- JavaScript
- スター
- 11.8k
- フォーク
- 7.9k
- 平均マージ
- 1日 11時間
- マージ済み PR(30日)
- 11
説明
In our project codebase there is an uncontrolled component that allows you to specify an initial value with value property (code examples are simplified just to show an idea):
const CustomInput = ({ value = '', onChange }) => {
const [uncontrolledValue, setUncontrolledValue] = useState(value);
const handleChange = (e) => {
setUncontrolledValue(e.target.value);
if (onChange) {
onChange(e.target.value);
}
}
return <input value={uncontrolledValue} onChange={handleChange} />
}
This component is used inside the complex form (other input components in this form are controlled). Resetting the form causes problems with this particular component because it doesn't update the internal value on props change. There is the article that recommends 2 possible solutions:
- rewrite component to be controlled one
- trigger force rerender of the component using
keyproperty
IMO there is another option available - make component controlled/uncontrolled depending on existence value property:
const CustomInput = ({ value: controlledValue, defaultValue = '', onChange }) => {
const [uncontrolledValue, setUncontrolledValue] = useState(defaultValue);
const isControlled = value !== undefined;
const value = isControlled ? controlledValue : uncontrolledValue;
const handleChange = (e) => {
if (!isControlled) {
setUncontrolledValue(e.target.value);
}
if (onChange) {
onChange(e.target.value);
}
}
return <input value={value} onChange={handleChange} />
}
This approach allows custom components to act as a standard <input /> element. I saw it in @kentcdodds video lesson and also in some popular libraries sources. But I can't find anything about such an approach in official react documentation. defaultValue is mentioned only here:
- https://reactjs.org/docs/dom-elements.html#value
- https://reactjs.org/docs/uncontrolled-components.html#default-values
Should this approach be added as a recommendation in You Probably Don't Need Derived State or Forms article? If not are there any pitfalls to consider it as bad practice / anti-pattern?
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず、issue でリンクされている「You Probably Don’t Need Derived State」、「Forms」、および「Uncontrolled Components」のドキュメントから始めてください。既存のガイダンスを、ここで説明されている controlled/uncontrolled component pattern と比較し、そのうえでドキュメントの変更が必要かどうか、またどこに配置すべきかを判断してください。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- javascript, react
- 領域
- documentation
- issue の種類
- ドキュメント
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 活発さ
- 停滞
- 明瞭さ
- 説明が足りない
- 初心者へのやさしさ
- 25/100