In HTML, form elements such as
<input>
,<textarea>
, and<select>
typically maintain their own state and update it based on user input.
https://reactjs.org/docs/forms.html#controlled-components
Can you give me an example?
Thanks.
CodePudding user response:
Simply said - maintain own state
means keep track of its own values, handle value changes etc.
If <select>
component maintain its state
and you select/change value, it saves that value in state
and show you result (<form>
does not know anything about that change). When sending <form>
, you have to ask components for their current values.
If <select>
does not maintain its state
, any changes to value are sent to its parent, usually <form>
. <form>
saves value in its state
(or send it to its parent) and gives <select>
new value to show (as changed props
). When sending form this way, you already have values stored in <form>
state.
Both ways have their pros and cons.
More about props and state here: https://reactjs.org/docs/state-and-lifecycle.html
CodePudding user response:
There are two main ways to use controls in react - controlled and uncontrolled. There are many examples on the web - simply search for those terms.
Uncontrolled is where the control is responsible for managing its value and you simply use the value it exposes - usually by handling an event such as "onChange" or by referencing the control. This is where the control is considered the source of truth - it maintains its own state.
<input type="text" ref={inputRef} onChange={handleOnChange}/>
Controlled is where your app is the source of truth and is usually managed via local state (eg useState hook). You use this state to tell the control, via its value property, what it should display regardless of what the control would otherwise display - you override its state. When a user modifies the controls value your state is updated, a component update is triggered and the control is provided the updated value to display.
<input type="text" value={value} onChange={handleOnChange} />
In a react app controls are usually implemented as "Controlled" as the parent component state or app state is considered the source of truth.