DEV Community

Cover image for Here's The Cool Thing About JSX: You Can Use HTML Tags In It.
Smithan kumar R
Smithan kumar R

Posted on

Here's The Cool Thing About JSX: You Can Use HTML Tags In It.

As you can see, the element is not in quotes to represent a string. It's like an HTML element, however we use it right in the JavaScript code!
This is called JSX, and it is a syntax extension to JavaScript. It allows us to build UI elements right in the JavaScript code!

ReactDOM.render(
  <h1>Hello, React!</h1>,
  document.getElementById('root')
);
Enter fullscreen mode Exit fullscreen mode

Expressions in JSX

We can use any JavaScript expression inside JSX using curly braces.

const name = "David";
const el = <p>Hello, {name}</p>;

ReactDOM.render(
  el,
  document.getElementById('root')
); 
Enter fullscreen mode Exit fullscreen mode

Attributes in JSX

We can specify attributes using quotes, just like in HTML:

JSX
When using a JavaScript expression as the attributes value, the quotes should not be used:

<div id="name"></div>
Enter fullscreen mode Exit fullscreen mode

When using a JavaScript expression as the attributes value, the quotes should not be used:

<div id={user.id}></div> 
Enter fullscreen mode Exit fullscreen mode

How Does JSX Work?

When the JSX expressions are compiled, they are converted into JavaScript objects, representing React elements.
React then uses these elements to build the corresponding HTML DOM and display it in the browser.

Let's create a counter app, that increments a counter variable every second and displays it on the page as a paragraph:

let counter = 0;

function show() {
  counter++;
  const el = <p>{counter}</p>;
  ReactDOM.render(
    el, document.getElementById('root')
  );
}

setInterval(show, 1000); 
Enter fullscreen mode Exit fullscreen mode

We use setInterval to call the show function every second and render the counter element on the page.

One of the great features of React is that it updates only the elements that need an update. You can inspect the HTML output of the example above and see that only the text in the paragraph gets updated every second.

JSX is a great tool for React in creating views. It has the simplicity of HTML. React's DOM manipulation works with it. The declarative nature makes it easy to understand.

Still, you should also know that JSX can make the code redundant, which makes a lot of developers hesitant to use it. But if you apply the proper unit testing, any potential issues can be found and resolved in time.

Top comments (0)