Yogesh Chauhan's Blog

What does JSX do in React?

in React on April 22, 2021

JSX is a syntax extension to JavaScript. It is useful to describe what User Interface should look like in React.

JSX has all the powers of JavaScript. Think of JSX like Hulk with Thanos’s hands. It’s more powerful JS that produces React elements. Like this element:


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


Why to use it?

As I have mentioned in the React basics post, React divides the application in small components. Each component has its own state. Eventually, it compiles everything to make the complex app but for developers it’s easier to manage everything in smaller pieces.

React is all about UI and JSX helps to focus on the overall UI creation for e.g. events handling, components states handling and finally preparing the data for the display.

You’re not required to use JSX. Only use it if you like it.

As per my point of view, React focus more on visual problem solving (frontend app creation) and JSX is helpful in working with User Interfaces. Furthermore, you also see the console errors logged by React. Overall debugging becomes so much interesting and easier.

Follow this guide to install and run your react app. What is React? Learn the basics

Now, one the app is up and running, we need to install few more packages to enable the JSX and ReactDOM.


Go inside the project by using this command:


cd first-react-app

Now, install the react-dom and jsx using the following commands one by one:


npm install react-dom
npm install jsx

There are few ways to install those packages. For e.g. you might want to install it globally or even install all together with react. It’s up to you.

After installing those packages, import ReactDOM into your /src/App.js and /src/index.js files using the import statement.

Like this:


import ReactDOM from "react-dom";

Embedding Expressions in JSX

Since we have the prerequisites ready we can add more code to the basic app and start building small components.

Let’s declare a simple variable with a name in it and try to run the app.

Before that, remove everything else from your /src/App.js and just keep this code:


import "./App.css";

function App() {
  return (
    <div className="App">
      <header className="App-header"></header>
    </div>
  );
}

export default App;



Go to your /src/index.js and remove all code and replace it with the following code:


import React from "react";
import ReactDOM from "react-dom";
import "./index.css";

const name = "Yogesh Chauhan";
const element = <h1>Hello, {name}</h1>;

ReactDOM.render(element, document.getElementById("root"));


In the example above, we are declaring a variable called name and then use it inside JSX. To use the variable we are using curly braces. We can use any valid JavaScript expression (like a math equation 1+2 or array.name) inside the curly braces in JSX.

After that adding JavaScript expression, just embed in HTML tags.

If your app is not running, use the following commands to run the app.


npm start

// or

yarn start

After that you’ll see your variable element displayed in h1 tags in the browser window. Like this:


Let’s try to call a function.


...
function greet(name, msg) {
  return msg + ", " + name.firstName;
}

const name = {
  firstName: "Yogesh",
  lastName: "Chauhan",
};

const element = <h1>{greet(name, "Hello")}!</h1>;
...

//Hello, Yogesh!


You can add if-else and loops in JSX as well — basically all JS things you can do. Remember Huld with Thanos Hand from the React Basics post?

HTML elements attributes in JSX

We can use quotes to define the string literals as element attributes. Like this:


...
const element = <h1 tabIndex="0">{greet(name, "Hello")}!</h1>;
...


If you want to add the img tag url dynamically, you can use curly braces to embed a JS expression in an img attribute:


...
const element = <img src={user.imageUrl}></img>;
...



Remember not to put quotes around the curly braces when you add JS Expression in an attribute.

JSX has all JS powers so it adopts the JS way for attribute names. The camelCase way. So, class becomes className and tabindex becomes tabIndex

Do we have to close empty tags like img?

In the example above, we have img tag closed but it’s not required. We can just close it with simple closing notation rather than the whole closing tag at the end. Just like this:


...
const element = <img src={user.imageUrl} />;
...


JSX stops XSS Injection Attacks

If you want to embed user inputs in JSX, don’t worry, it’s safe. What ReactDOM does is it escapes values embedded in JSX. That means it converts everything in string and then renders which stops XSS (cross-site-scripting) attacks.

JSX is more like creating objects

Look at this code:


const element = (
  <h1 className="greeting">
    Hello, world!
  </h1>
);


Now, checkout this code:


const element = React.createElement(
  'h1',
  {className: 'greeting'},
  'Hello, world!'
);


Both of the code examples above are identical but the syntax is different.

It’s because Babel does the compilation and brings JSX down to React.createElement() calls.


Why do we need that?

React.createElement() performs a few checks so and make sure that the code doesn’t have bugs.

After the checks it creates an object (React Element) like this:


const element = {
  type: 'h1',
  props: {
    className: 'greeting',
    children: 'Hello, world!'
  }
};


In fact, it creates more complex object. The above code is a simplified version.

React goes for that React Object and uses their props to construct the HTML DOM. That’s how it keeps the DOM up to date every time you make change into your code.

We can also use those props by calling the object and using a dot operator.

You can always check the official React docs to explore more.


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to convert an object from API to JSON array in Angular 9?AngularHow to change CSS with JavaScript?CSStransform-origin Property in CSSCSSWhat does JSX do in React?React@forward modules with a prefix in SCSS (Sass)SCSSIntroduction to Angular modules Part 3: NgModules vs JavaScript modules and Angular librariesAngular