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

Embedding JavaScript in JSX

Hello, students! In the previous topic, we learned about the syntax and benefits of JSX.

In this class, we will learn about incorporating JavaScript into JSX.

With the embedding of JavaScript in JSX, we can write JavaScript code within JSX tags.

This allows us to create more powerful and flexible React components.

Basic JavaScript Embedding

Basic JavaScript embedding is done using the { and } syntax.

For example, the following code embeds a snippet of JavaScript code within a <div> tag:

<div>
  {
    // JavaScript code
    const message = "Hello, world!";
  }
</div>

This code renders the following output:

Hello, world!

Advanced JavaScript Embedding

We can also embed advanced JavaScript in JSX using block syntax.

For example, the following code embeds a snippet of JavaScript code within a <div> tag using block syntax:

<div>
  {(
    // JavaScript code
    const message = "Hello, world!";
  ) => (
    // Rendering JavaScript code
    <p>{message}</p>
  )}
</div>

This code renders the following output:

Hello, world!

Example of JavaScript Embedding

Let’s see an example of how to use JavaScript embedding to render a list of products:

const products = [
  {
    name: "Product 1",
    price: 100,
  },
  {
    name: "Product 2",
    price: 200,
  },
];

const MyComponent = () => {
  return (
    <div>
      <ul>
        {products.map((product) => (
          {
            // JavaScript Embedding
            const productPrice = product.price * 1.1;

            // Rendering JavaScript code
            <li key={product.id}>{product.name} - $ {productPrice}</li>
          })}
      </ul>
    </div>
  );
};

This code renders a list of products with prices increased by 10%.

The code uses JavaScript embedding to calculate the increased price of the product and render it in the list.

Conclusion

In today’s topic, we learned about embedding JavaScript in JSX.

With JavaScript embedding, we can write JavaScript code within JSX tags.

This allows us to create more powerful and flexible React components.

I hope you understood the incorporation of JavaScript in JSX, if you have any questions, leave a comment.

Entrar na conversa
Rolar para cima