InterviewSolution
| 1. |
What are the differences between controlled and uncontrolled components? |
||||||||||||||||||||||||||||||||
|
Answer» Controlled and uncontrolled components are just different approaches to handling input from elements in react.
When a user enters data inside the input element of a controlled component, onChange function gets triggered and inside the code, we check whether the value entered is valid or invalid. If the value is valid, we change the state and re-render the input element with the new value. Example of a controlled component: function FormValidation(PROPS) {let [inputValue, setInputValue] = useState("");let updateInput = e => { setInputValue(e.target.value);};return ( <div> <form> <input type="text" value={inputValue} onChange={updateInput} /> </form> </div>);}As one can see in the code above, the value of the input element is determined by the state of the inputValue variable. Any changes made to the input element is handled by the updateInput function.
The state of the input element is handled by the DOM. WHENEVER the value of the input element is changed, event-based callbacks are not called. Basically, react does not perform any action when there are changes made to the input element. Whenever use enters data inside the input field, the updated data is shown directly. To access the value of the input element, we can use ref. Example of an uncontrolled component: function FormValidation(props) {let inputValue = React.createRef();let handleSubmit = e => { alert(`Input value: ${inputValue.current.value}`); e.preventDefault();};return ( <div> <form onSubmit={handleSubmit}> <input type="text" ref={inputValue} /> <button type="submit">Submit</button> </form> </div>);}As one can see in the code above, we are not using onChange function to govern the changes made to the input element. Instead, we are using ref to access the value of the input element. |
|||||||||||||||||||||||||||||||||