- In React, "two-way binding" is a pattern where changes to a form input field are immediately reflected in the component's state, and changes to the component's state are immediately reflected in the form input field. This pattern is often used in forms or other user input scenarios where you want to keep the component's state in sync with the user input.
- However, unlike some other frameworks, React does not provide a built-in two-way binding mechanism. Instead, you can implement two-way binding in React by using controlled components.
- A controlled component is a form input element that is controlled by React through its state. When a user types into a controlled input element, the onChange event is triggered, which updates the component's state with the new value. The component then re-renders, and the new value is reflected in the form input field.
- Here's an example of how to implement two-way binding in React using a controlled component:
import { useState } from 'react';
function MyForm() {
const [inputValue, setInputValue] = useState('');
function handleInputChange(event) {
setInputValue(event.target.value);
}
return (
<div>
<input type="text" value={inputValue} onChange={handleInputChange} />
<p>You typed: {inputValue}</p>
</div>
);
}
- In this example, the value prop is set to the inputValue state variable, which is updated in the handleInputChange function when the user types into the input field. The onChange event triggers the function, which updates the state with the new value. The new value is then reflected in the input field, and also in the p element below it.
- By using a controlled component, we can achieve two-way binding in React. The input field is controlled by React through its state, and changes to the input field immediately update the state, which is reflected in the component's UI. Similarly, changes to the component's state immediately update the input field, providing two-way binding.
No comments:
Post a Comment