In React, there are two main approaches to handling form inputs:
Controlled Components provide more control and validation, while uncontrolled components are simpler and useful for basic forms of intermittent value access.
These are form inputs whose values are controlled by React State. The state variables are updated whenever the value of the input changes, and the value of the input is set explicitly through the value prop.
The onChange event handler is used to update the state.
import React, { useState } from "react"; function ControlledComponent() { const [name, setName] = useState("") const handleChange = (e) => { setName(e.target.value); } return( ); }
In the above example, the name state variable controls the input field's value. The handleChange function updates the name state whenever the input value changes and the input value is set to the Current value of the name state variable through the value prop.
Uncontrolled Components are form inputs that manage their state internally, rather than being controlled by React State. You can access the current value of the input using a ref after the form is submitted or whenever needed.
import React, { useRef } from "react"; function UncontrolledComponent() { const inputRef = useRef(null); const handleSubmit = (e) => { e.preventDefault(); console.log(inputRef.current.value); }; return(); }
In this above example, the inputRef is used to create a ref for the input field. The handleSubmit function accesses the current value of the input using inputRef.current.value. The form submission logic can be implemented to utilize the input value as required.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3