Čo je to sakra JSX a prečo by si ho mal používať na vytváranie svojich aplikácií React

Ako vývojári používame rôzne nástroje a balíčky otvorených zdrojov, ktoré nám uľahčujú prácu. Niektoré z nich sú v komunite tak rozšírené, že sa javia ako pôvodné v JavaScripte. Ale nie sú a môžu zásadne zmeniť spôsob denného písania kódu .

Jednou z týchto technológií, ktorú už pravdepodobne používate, je JSX - rozšírenie syntaxe XML podobné JavaScriptu . Cieľom tohto tímu, ktorý vytvoril tím na Facebooku, je zjednodušiť prácu vývojárov. Ako hovorí špecifikácia, dôvodom pre vytvorenie JSX bolo:

"... definovať stručnú a známu syntax pre definovanie stromových štruktúr s atribútmi." ~ JSX Spec

Pravdepodobne si teraz hovoríte: „Hej, Ryane, znie to skvele, ale už sa dostaň k kódu “, takže tu je náš prvý príklad.

const helloWorld = 

Hello, World!

;

A je to!

Fragment kódu vyššie vyzerá dobre, ale už ste niekedy prestali premýšľať o jeho sile? JSX to umožňuje, aby sme mohli prechádzať okolo stromových štruktúr zložených z prvkov HTML alebo React , akoby išlo o štandardné hodnoty JavaScriptu.

Aj keď pri písaní Reactu nemusíte používať JSX (alebo použiť React, aby ste JSX vyskúšali), nemožno poprieť, že je dôležitou súčasťou ekosystému React, takže sa ponorme a pozrime sa, čo sa deje pod kapotou.

Začíname s JSX

Prvá vec, ktorú si musíte uvedomiť pri použití syntaxe JSX, je, že React musí byť v rozsahu. Je to spôsobené tým, ako sa kompiluje. Vezmite si napríklad tento komponent:

function Hello() { return 

Hello, World!

}

V zákulisí je každý prvok vykreslený Hellokomponentom transponovaný do React.createElementhovoru.

V tomto prípade:

function Hello() { return React.createElement("h1", {}, "Hello, World!")}

To isté platí pre vnorené prvky. Dva nižšie uvedené príklady by nakoniec priniesli rovnaké označenie.

// Example 1: Using JSX syntaxfunction Nav() { return ( 
    
  • Home
  • About
  • Portfolio
  • Contact
);}
// Example 2: Not using JSX syntaxfunction Nav() { return ( React.createElement( "ul", {}, React.createElement("li", null, "Home"), React.createElement("li", null, "About"), React.createElement("li", null, "Portfolio"), React.createElement("li", null, "Contact") ) );}

React.createElement

Keď React vytvorí prvky, zavolá túto metódu, ktorá vyžaduje tri argumenty.

  1. Názov prvku
  2. Objekt predstavujúci rekvizity prvku
  3. Pole podradených prvkov

Tu si treba uvedomiť, že React interpretuje malé prvky ako prvky HTML a Pascal (napr. ThisIsPascalCase) ako vlastné komponenty. Z tohto dôvodu by sa nasledujúce príklady interpretovali odlišne.

// 1. HTML elementReact.createElement("div", null, "Some content text here")
// 2. React elementReact.createElement(Div, null, "Some content text here")

Prvý príklad by vygeneroval a iv> with the s tring "Some content text here" as its child. However, the second version would throw an error (unless, of course, a custom comp onent <Div /> was in sco pe) because is undefined.

Props in JSX

When working in React, your components often render children and need to pass them data in order for the children to render properly. These are called props.

I like to think of React components as a group of friends. And what do friends do? They give each other props. Thankfully, JSX offers us a number of ways to do that.

// 1. Props defaulted to true
// 2. String literals
// 3. JavaScript expressions
// 4. Spread attributes

But beware! You cannot pass if statements or for loops as props because they are statements, not expressions.

Children in JSX

As you are building your app, you eventually start having components render children. And then those components sometimes have to render children. And so on and so forth.

Since JSX is meant to make it easy for us to reason about tree-like structures of elements, it makes all of this very easy. Basically, whatever elements a component returns become its children.

There are four ways to render child elements using JSX:

Strings

This is the simplest example of JSX children. In the case below, React creates a <h1> HTML element with one child. The child, however, is not another HTML element, just a simple string.

function AlertBanner() { return ( 

Your bill is due in 2 days

)}

JSX Elements

This is probably the use case that new React developers would be most familiar with. In the component below, we’re returning an HTML child (the er>), which has two children of it s own &lt;Na v /> and &lt;ProfilePic /> both of which are custom defined JSX elements.

function Header(props) { return ( )}

Expressions

Expressions allow us to easily render elements in our UI that are the result of a JavaScript computation. A simple example of this would be basic addition.

Say we have a component called /> that renders information about a bill or receipt. Let’s assume it takes one prop c alled total that represents the pre-tax cost and another prop taxRate, which represents the applicable tax rate.

Using expressions, we can easily render out some useful information for our users!

function BillFooter(props) { return ( 
Tax: {props.total * props.taxRate}
Total: {props.total + props.total * props.taxRate}
);}

Functions

With functions, we can programmatically create elements and structures, which React will then render for us. This makes it easy to create multiple instances of a component or render repeated UI elements.

As an example, let’s use JavaScript’s .map() function to create a navigation bar.

// Array of page informationconst pages = [ { id: 1, text: "Home", link: "/" }, { id: 2, text: "Portfolio", link: "/portfolio" }, { id: 3, text: "Contact", link: "/contact" }];// Renders a 
    
    with programmatically created
  • childrenfunction Nav() { return (
      {pages.map(page => { return (
    • {page.text}
    • ); })}
    );}

Now, if we want to add a new page to our site, all we need to do is add a new object to the pages array and React will take care of the rest!

Take note of the key prop. Our function returns an array of sibling elements, in this case <li>s, and React needs a way to keep track of which mounts, unmounts or updates. To do that, it relies on this unique identifier for each element.

Use the tools!

Sure, you can write React applications without JSX, but I’m not really sure why you’d want to.

The ability JSX gives us to pass around elements in JavaScript like they were first-class citizen lends itself well to working with the rest of the React ecosystem. So well, in fact, you may have been writing it every day and not even known it.

Bottom line: just use JSX. You’ll be happy you did.