React JS Tutorial: Controlled Components 🎯

beginner
21 min

React JS Tutorial: Controlled Components 🎯

Welcome back to CodeYourCraft! Today, we're diving deep into React JS, exploring a fundamental concept known as Controlled Components. Let's get started!

What are Controlled Components? πŸ“

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.

Why use Controlled Components? πŸ’‘

  • Consistency: By controlling the component's state in React, we can ensure that the component's value is always consistent with the state.
  • Validation and Form Handling: Controlled components make it easier to validate user input and handle form submission.

Creating a Controlled Component 🎯

Let's create a simple example of a Controlled Componentβ€”a form with an input field and a button for submitting the form.

jsx
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.

Quick Quiz
Question 1 of 1

In the example above, what does the `useState` hook do?

Challenges and Solutions πŸ’‘

Challenge 1: Two-way data binding

With Controlled Components, we have one-way data binding. How can we achieve two-way data binding?

  • Solution: To achieve two-way data binding, we can use 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.

Challenge 2: Using Controlled Components in a class component

Can Controlled Components be used in class components?

  • Solution: Yes, Controlled Components can be used in class components by following similar principles. Instead of hooks, we use the this.state and this.setState methods to manage the state.

Wrapping Up βœ…

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! πŸš€