Requirements
- React.js
Introduction
Normally HTML elements that are used in forms keep their own state and updates based on user input, in React we tend to deal with mutable states using . Working with forms in React the approach is usually to make React state to be the "single source of truth", making the component "controlled". This is not the only way to work this out, so let's check how each works.
Controlled
The React component that renders a form also controls what happens on user input by mutating state via :
import React, { useState } from "react"; function Controlled() { const [state, setState] = useState(""); function logValue() { console.log(state); } return ( <form> <input type="text" value={state} onChange={(e) => setState(e.target.value)} /> <button onClick={logValue}>Get Value</button> </form> ); }
Here you grab form data by grabbing the React State.
Uncontrolled
Although is recommended in most cases to use the controlled approach, you can also use the "uncontrolled" alternative where form data is handled by the DOM itself, unattached from React state:
import React, { useRef } from "react"; function Uncontrolled() { const inputRef = useRef(); function logValue() { console.log(inputRef.current.value); } return ( <form> <input type="text" ref={inputRef} /> <button onClick={logValue}>Get Value</button> </form> ); }
Here you grab form data by grabbing the input reference.
