Understanding React elements and JSX
Tags: react, webdev, javascript
Published: 2020-04-10 17:41:04

<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9kLrAfGF2nbVGo9n" /><figcaption>Photo by <a href="https://unsplash.com/@flowforfrank?utm_source=medium&amp;utm_medium=referral">Ferenc Almasi</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s start by writing a simple piece of code to display a <strong><em>“Hello World”</em> </strong>message, using just <strong>vanilla Javascript and browser APIs</strong>.</p><p>First, let’s create a root div in our body section:</p>

```html
<body>
  <div id="root"></div>
</body>
```

<p>We will now <strong>create a new </strong><strong>div</strong> with the <em>Hello World</em> message and <strong>append</strong> it to our root div using Javascript.</p><p>We need to <strong>get that root </strong><strong>div</strong> element first:</p>
```javascript
const rootElement = document.getElementById('root');

```
<p>Then<strong> create a new div</strong> and add the text content:</p>
```javascript
const element = document.createElement('div');
element.textContent = 'Hello World';
```
<p>And finally <strong>append</strong> this new child element to the root element:</p>
```javascript
rootElement.appendChild(element);
```
<p>That’s all we need to display a <em>Hello World</em> message. Here is the final code:</p>

{%gist https://gist.github.com/francodalessio/cc7de13109fac4bd3e6a30485ac050d3 %}

<h3>Let’s do the same with React</h3><p>React <strong>controls and updates the DOM</strong> using the same APIs we used in our previous example. But instead of creating DOM elements, we’ll create <strong>React elements</strong>. react-dom will take care of <strong>converting them into DOM elements</strong> and putting them into the page.</p><h4>What is a React element?</h4><p>Think about React elements as a <strong>description of what you see on the screen. </strong>React <strong>reads these objects and uses them to construct the DOM</strong> and keep it up to date.</p><blockquote>Don’t confuse React elements with <strong>components</strong>. Elements are what components are “made of”, and you must first understand what they are before jumping ahead into components.</blockquote><h4>The createElement API</h4><p>For this first React example we’ll use React’s <strong>createElement API.</strong></p><p>We need to get React on the page. We'll add <strong>react</strong> and <strong>react-dom</strong> directly from <a href="https://unpkg.com/">unpkg</a> as script tags.</p>

<p>Then, instead of creating a div element we create a <strong>React element</strong>. The API for react.createElement is:</p>
```javascript
function createElement(elementType, props, ...children) {}
```
<p>We don’t have any props in our example, so we’d create our element like this:</p>
```javascript
const element = React.createElement("div", null, 'Hello World');
```
<p>The text <em>Hello World</em> is our element’s child.</p><p>We can see this <strong>React element</strong> by logging it to the console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*I371zGvt8laD7-jcC54syg.png" /></figure><p>We don’t get a DOM element, but an <strong>object</strong>. Remember we said earlier that React elements are <strong>objects that describe what you see on the screen.</strong></p><p>You can see that <strong>children</strong> is actually inside the <strong>props</strong> object.</p><p>These two lines are <strong>equivalent</strong> and both correct:</p>
```javascript
const element = React.createElement("div", null, 'Hello World');
const element = React.createElement("div", {children: 'Hello World'});
```
<blockquote>You can pass the <strong>children</strong> inside the <strong>props</strong> object or as the <strong>third parameter</strong> of the function.</blockquote><p>Ok, we’ve got our <strong>React element</strong>. Now what?</p><p>Instead of appending this element to the root element, as we did in the first example with our DOM element, we’ll let <strong>react-dom</strong> handle all that:</p>
```javascript
ReactDOM.render(element, rootElement);
```
<p>The end result will be the same as the first example. This is the final code:</p>

{%gist https://gist.github.com/francodalessio/874a61159dbab42b307392440334d78b %}

<h3>Finally, let’s use JSX! 🚀</h3><p>This react.createElement syntax works, but is not the best. Fortunately, we have another option, which is also the <strong>standard way</strong> the community uses to create React elements.</p><h4>What is JSX? 🤔</h4><p>JSX is an <strong>extension to Javascript</strong> to support syntax that<strong> <em>looks like </em>the HTML code</strong> you would write to create these DOM elements.</p><p>So we can create our element by just doing this:</p>
```javascript
const element = <div>Hello World</div>;
```
<p>Sweet, right?</p><h4>Why JSX?</h4><p><strong>React doesn’t require you to use JSX</strong>. You can use the createElement API and everything will work in the same way.</p><p>However, JSX is of great help. React is based on the principle that <strong>rendering logic is coupled with UI logic</strong>. Instead of separating them by putting markup and logic in separate files, React uses <strong>components </strong>that contain both.</p><p>Using JSX is helpful because it allows you to <strong>easily work with UI inside Javascript code.</strong></p><h4>JSX is awesome! But we still have a problem…</h4><p>The browser does not understand JSX natively, so it needs to be <strong>compiled</strong>. That’s where <a href="https://babeljs.io/"><strong>Babel</strong></a><strong> </strong>comes in. It will convert JSX syntax to <strong>something the browser can understand.</strong></p><p>What do you think that will be?</p><p>Exactly: it will use <strong>react.createElement API</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*HHliaZ5VAwrczGOAiiPWgA.png" /></figure><p>You can try this yourself in the <a href="https://babeljs.io/repl">Babel’s website</a>.</p><h4>Adding props</h4><p>In the last example, the second argument to createElement is null because we have no <strong>props</strong>.</p><p>We can include a className and see how Babel translates it to be the <strong>second argument</strong> of the createElement function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*HmfyDwyeG-odk-nV2pQH9w.png" /></figure><h4>Adding children</h4><p>We can also add more children. Right now, the only child is the <em>Hello World</em> text, but we can add more:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LzAXHU9aZOMggf7RtkHHDg.png" /></figure><p>You can see that now the third argument of the createElement function is not just a string. Instead it’s <strong>a second React element of type </strong><strong>p</strong>, which has the <em>Hello World</em> string text as its child.</p><h3>The power of JSX 💪</h3><p>With JSX you can do more than just creating React elements. Let’s take a look at everything JSX has to offer.</p><h4>Embedding expressions</h4><p>Using <strong>curly braces</strong>, you can embed any Javascript expression inside JSX.</p><p>For example, you can do this:</p>

```javascript
const name = 'John';
const element = <div>Hello {name}</div>
ReactDOM.render(
 element,
 document.getElementById('root')
);
```

<p>And Hello John will be displayed on the page.</p>

<p>But it doesn’t have to be just a static string value, you can embed <strong>any Javascript expression:</strong></p>

```javascript
const element = <div>2+2 = {2+2}</div>
ReactDOM.render(
 element,
 document.getElementById('root')
);
```

<p>In this case, 2+2 = 4 will be displayed on the page.</p><h4>JSX is an expression</h4><p>We know that JSX will be <strong>compiled</strong> to be a react.createElement function, and that function will return an <strong>object</strong>.</p><p>That means that we can <strong>assign JSX to variables:</strong></p>
```javascript
const element = <div>Hello World</div>
```
<p>Or, for example, <strong>return JSX from functions:</strong></p>
```javascript
const getAgeDescription = (age) => {
  if (age < 50) {
    return <h1>You're young</h1>;
  } 
  return <h1>You're old</h1>;
}
```
<h4>Specifying attributes</h4><p>You can use <strong>quotes</strong> to specify <strong>string literals as attributes:</strong></p>
```javascript
const element = <img src='http://xyz.com/img.jpg'></img>;
```
<p>Or <strong>curly braces</strong> to embed a <strong>Javascript expression:</strong></p>
```javascript
const user = { name: 'John', profileImgUrl: 'http://xyz.com/img.jpg' };
const element = <img src={user.profileImgUrl}></img>;
```

<p>JSX uses <strong>camelCase</strong> for attributes, and there’re some changes you have to keep in mind. As some words are reserved by Javascript, <strong>some attributes change its name when using JSX.</strong></p><p>For example, you don’t use class in JSX, but className. You don’t use for in a label element, you use htmlFor .</p><p>To read more about these exceptions and all the <strong>accepted attributes</strong> in JSX you can check the <a href="https://reactjs.org/docs/dom-elements.html"><strong>official documentation</strong></a><strong>.</strong></p><h4>Self-closing tags</h4><p>If an element doesn’t have any children, you can close it with /&gt;:</p>
```javascript
const element = <img src={user.profileImgUrl} />;
```
<h3>That’s all!</h3><p><strong>Understanding how JSX is compiled is important because it will make you more effective at using JSX.</strong> I encourage you to take you React code to the Babel website to see how it is compiled and how it looks using the createElement API.</p><p>I’ll leave this here. There are a lot of things I could continue writing about (rendering, components, etc.), but I’ll do so in separate articles. <strong>JSX is an important concept</strong> and you should <strong>understand it well before moving</strong> <strong>on</strong> to other stuff.</p><p>Thanks for reading ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3b7af356db4" width="1" height="1">