Conteúdo do curso
Immersion in React: Comprehensive Course for Beginners
Sobre a Aula

Creation and Reuse of Components

Hello, students! In the previous topic, we learned about the concept of componentization.

Here, let’s learn about how to create and reuse components.

Creating Components

To create a component, we need to define a class that inherits from React.Component.

The class should have a render() method that returns the JSX code to be rendered by the component.

For example, the following code creates a component that renders a header:

class Header extends React.Component {
  render() {
    return (
      <h1>My Header</h1>
    );
  }
}

Reusing Components

To reuse a component, we need to import it into our code and instantiate it.

For example, the following code imports the Header component and inserts it into a page:

import React from "react";
import Header from "./components/Header";

class App extends React.Component {
  render() {
    return (
      <div>
        <Header />
      </div>
    );
  }
}

Example of Component Reuse

Let’s see an example of how to reuse a component to create a list of products:

The following code renders a list of products:

class ProductList extends React.Component {
  render() {
    return (
      <ul>
        {this.props.products.map((product) => (
          <li key={product.id}>{product.name}</li>
        ))}
      </ul>
    );
  }
}

class App extends React.Component {
  render() {
    return (
      <div>
        <ProductList products={this.state.products} />
      </div>
    );
  }
}

This code is quite complex and hard to maintain.

We can divide this code into smaller and more manageable components, as follows:

class Product extends React.Component {
  render() {
    return (
      <li key={this.props.id}>{this.props.name}</li>
    );
  }
}

class ProductList extends React.Component {
  render() {
    return (
      <ul>
        {this.props.products.map((product) => (
          <Product key={product.id} name={product.name} />
        ))}
      </ul>
    );
  }
}

class App extends React.Component {
  render() {
    return (
      <div>
        <ProductList products={this.state.products} />
      </div>
    );
  }
}

This code is easier to understand and maintain.

Conclusion

Creating and reusing components are two essential skills for React application development.

When creating components, we should focus on making them reusable.

To achieve this, we should avoid couplings between components and use props to pass data between them.

When reusing components, we should ensure that we are using the latest version of the component.

I hope you understood how to create and reuse components. If not, leave your question in the comments.

Entrar na conversa
Rolar para cima