Conteúdo do curso
Advanced React: Props and State
Sobre a Aula

Implementation of practical examples to solidify the understanding of Props and State

Firstly, let’s review how to pass data between components using props. Imagine a to-do list component that needs to display multiple tasks.

Each task can be a child component, receiving its data from the parent component through props. Here’s a simplified example:

// Parent component
function TaskList() {
  const tasks = ["Study React", "Go shopping", "Exercise"];

  return (
    <div>
      {tasks.map((task, index) => (
        <Task key={index} text={task} />
      ))}
    </div>
  );
}

// Child component
function Task({ text }) {
  return <div>{text}</div>;
}

Here, the parent component TaskList passes each task to the child component Task through the prop text.

Now, let’s address how state is used in practice. Consider a registration form where the user fills in the fields, and the data is stored in the component’s state.

Here’s a basic example:

// Form component
function RegistrationForm() {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");

  const handleSubmit = (event) => {
    event.preventDefault();
    // Here you can send the data to the server or perform other actions
    console.log("Name:", name);
    console.log("Email:", email);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder="Name" />
      <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Email" />
      <button type="submit">Submit</button>
    </form>
  );
}

In this example, state is used to store the values of the input fields (name and email). Whenever the user types something, the state is updated and reflects what was typed.

With these practical examples, you will solidify your understanding of how to efficiently use Props and State in React applications.

Try creating your own examples and explore different scenarios to further enhance your skills!

Entrar na conversa
Rolar para cima