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

Best Practices When Using JSX

Hello, students! In the previous topic, we learned about embedding JavaScript in JSX.

Here, we will learn about some best practices when using JSX.

By following these practices, you’ll be able to write more efficient and readable JSX code.

Use Concise JSX Tags

Use concise JSX tags to make your code more readable.

For example, instead of using the following tag:

<div style={{ color: "red" }}>
  Hello, world!
</div>

Use the following tag:

<div style="color: red">Hello, world!</div>

Use Block Syntax for JavaScript Embedding

Block syntax is a more concise and readable way to embed JavaScript in JSX.

For example, instead of using the following tag:

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

Use the following tag:

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

Avoid using empty JSX tags.

If you don’t need to render anything inside a JSX tag, use null instead of an empty tag.

For example, the following code is better than the code below:

<div>
  <h1></h1>
  <p></p>
</div>
<div>
  <h1>{null}</h1>
  <p>{null}</p>
</div>

Use of Variables

Use variables to store values that you need to use multiple times in your JSX code.

This will make your code more readable and easy to maintain.

For example, the following code is better than the code below:

<div>
  <h1>Hello, {name}</h1>
  <p>My name is {name}</p>
</div>
const name = "John";

<div>
  <h1>Hello, {name}</h1>
  <p>My name is {name}</p>
</div>

Use of Functions

Use functions to group related JSX code.

This will make your code more modular and easy to reuse.

For example, the following code is better than the code below:

<div>
  <h1>Hello, {name}</h1>
  <p>My name is {name}</p>
</div>
const renderName = (name) => (
  <div>
    <h1>Hello, {name}</h1>
    <p>My name is {name}</p>
  </div>
);

renderName("John");

Use TypeScript to Type Your JSX Code

TypeScript is a programming language that provides static typing.

Using TypeScript to type your JSX code can help prevent errors and make your code more readable.

Conclusion

By following these best practices, you’ll be able to write more efficient and readable JSX code.

I hope you’ve understood the best practices when using JSX.

In the next module, we’ll learn about components in React.

Components are fundamental building blocks of React.

With components, we can create reusable and easy-to-maintain user interfaces.

If you have any questions, leave your comment.

Until then, keep studying!

Entrar na conversa
Rolar para cima