Children

JSX allows you to define children to describe the tree of elements and compose complex UIs.

A basic example is a link with text inside it, as follows:

  <a href="https://dev.education">Click me!</a>

This would be transpiled into the following:

  React.createElement( 
"a",
{ href: "https://www.dev.education" },
"Click me!"
);

Our link can be enclosed inside a div element for some layout requirements, and the JSX snippet to achieve that is as follows:

  <div> 
<a href="https://www.dev.education">Click me!</a>
</div>

The JavaScript equivalent is as follows:

  React.createElement( 
"div",
null,
React.createElement(
"a",
{ href: "https://www.dev.education" },
"Click me!"
)
);

It should now be clear how the XML-like syntax of JSX makes everything more readable and maintainable, but it is always important to know the JavaScript parallel of our JSX to have control over the creation of elements.

The good part is that we are not limited to having elements as children of elements, but we can use JavaScript expressions, such as functions or variables.

To do this, we have to enclose the expression within curly braces:

  <div> 
Hello, {variable}.
I'm a {() => console.log('Function')}.
</div>

The same applies to non-string attributes, as follows:

  <a href={this.createLink()}>Click me!</a>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset