Conteúdo do curso
React.js: Understand and Apply the Lifecycle
Sobre a Aula

First steps with JSX

JSX is a syntax extension for JavaScript. It looks like HTML, but is used within JavaScript code. JSX makes writing React components easier and more intuitive.

Why Use JSX?

JSX helps create React elements in a simple way. Instead of using JavaScript functions, you use a syntax that resembles HTML. This makes the code more readable.

How Does JSX Work?

JSX transforms into React.createElement() calls. This process is done during compilation. Here’s a basic example:

const element = <h1>Hello, world!</h1>;

This code creates a React h1 element that displays “Hello, world!”. Behind the scenes, it transforms into:

const element = React.createElement('h1', null, 'Hello, world!');

Embedding JavaScript Expressions

You can use JavaScript expressions inside JSX. Place the expressions between curly braces {}. For example:

const name = 'Alice';
const element = <h1>Hello, {name}!</h1>;

This code will display “Hello, Alice!”.

Attributes in JSX

In JSX, you can pass attributes to elements, like in HTML. For example:

const element = <img src="logo.png" alt="Logo" />;

Note that some HTML attributes have different names in JSX. For example, class becomes className, and for becomes htmlFor.

Components and JSX

JSX can also be used to represent React components. For example:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara" />;

Here, the Welcome component receives a name property and uses it to display a welcome message.

Conclusion

JSX makes it easier to create and manipulate React elements. It combines the ease of HTML with the power of JavaScript. Now, practice creating your own elements and components using JSX.

Entrar na conversa
Rolar para cima