Welcome back to CodeYourCraft! Today, we're diving deep into React JS, exploring a fundamental concept known as Controlled Components. Let's get started!
In React, a controlled component is a component where the value is controlled by a React state, and the input's value property is set to that state. This approach gives us more control over how the component behaves, especially when handling user input.
Let's create a simple example of a Controlled Componentβa form with an input field and a button for submitting the form.
import React, { useState } from 'react';
function ControlledForm() {
const [name, setName] = useState('');
function handleSubmit(e) {
e.preventDefault();
console.log('Name:', name);
}
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={name} onChange={e => setName(e.target.value)} />
</label>
<button type="submit">Submit</button>
</form>
);
}
export default ControlledForm;In this example, we have a functional component called ControlledForm. We use the useState hook to declare a state variable name and its corresponding state updater setName. Inside the form, we set the value of the input field to name and handle the input change using the onChange event. The form submission is handled by the handleSubmit function.
In the example above, what does the `useState` hook do?
With Controlled Components, we have one-way data binding. How can we achieve two-way data binding?
useState and the ref hook. This allows the component to read the current value of a DOM element and update it when the state changes.Can Controlled Components be used in class components?
this.state and this.setState methods to manage the state.Controlled Components are a powerful tool for managing user input in React. By understanding and mastering Controlled Components, you'll be well-equipped to build complex forms and applications.
Remember, practice makes perfect! Try creating your own Controlled Components and exploring more advanced examples to deepen your understanding of this concept. Happy coding! π