What is JSX and why to use it?
© https://reactjs.org/

What is JSX and why to use it?

Introduction to JSX in React

ByMario Kandut

honey pot logo

Europe’s developer-focused job platform

Let companies apply to you

Developer-focused, salary and tech stack upfront.

Just one profile, no job applications!

One of the main concepts, in the React world is JSX. Let's find out what JSX is.

Get started with JSX

JSX is a syntax extension to JavaScript and looks like this:

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

💰 The Pragmatic Programmer: journey to mastery. 💰 One of the best books in software development, sold over 200,000 times.

If you've not worked with React before, it may look a bit funny at first, but this syntax is neither a string nor HTML. Maybe it reminds you on a template language, but it is a syntax extension to JavaScript and comes with all the JavaScript features.

JSX produces React elements and is mainly used with React to describe what the UI should look like.

Why JSX?

React embraces the fact that rendering logic is inherently coupled with other UI logic: how events are handled, how the state changes over time, and how the data is prepared for display.

React is avoiding this artificial separation of technologies markup and logic (others like that approach, Angular), React separates concerns with loosely coupled units or components that contain both.

React doesn't require using JSX, though it may be helpful and React can show more useful error and warning messages.

JavaScript Expressions in JSX

Since JSX is a syntax extension to JavaScript you can use any valid JavaScript expression. Let's try it out. Let's declare the constant name a string and render it.

const name = 'Mario';
const element = <h1>Hello, {name}</h1>;

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

Let's try it with a function:

function formatName(user) {
  return user.firstName + ' ' + user.lastName;
}

const user = {
  firstName: 'Mario',
  lastName: 'Kandut',
};

const element = <h1>Hello, {formatName(user)}!</h1>;

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

When splitting JSX over multiple lines for readability, it is recommended to wrap it in parentheses to avoid the pitfalls of automatic semicolon insertion, read more at Stackoverflow.

Use JSX in an expression

After compilation JSX becomes regular JavaScript. JSX is an expression too, hence you can use JSX inside of if statements and for loops, assign it to variables, accept it as arguments, and return it from functions.

function getGreeting(user) {
  if (user) {
    return <h1>Hello, {formatName(user)}!</h1>;
  }
  return <h1>Hello, Stranger.</h1>;
}

Attributes in JSX

You can use quotes to specify string literals as attributes:

const element = <div tabIndex="0"></div>;

You can also use curly braces to embed a JavaScript expression in an attribute:

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

Don’t put quotes around curly braces, it's either use quotes (for string values) or curly braces (for expressions).

Since JSX is closer to JavaScript than to HTML, React DOM uses camelCase property naming convention. Use className for class and tabIndex for tabindex.

Specifying Children with JSX

If a tag is empty, you can close it immediately with, like XML:

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

JSX tags may contain children:

const element = (
  <div>
    <h1>Hello!</h1>
    <h2>Good to see you here.</h2>
  </div>
);

Security (XSS)

JSX prevents Injection Attacks like XSS. It is safe to embed user input like this:

const title = response.potentiallyMaliciousInput;
// This is safe:
const element = <h1>{title}</h1>;

By default, React DOM escapes any values embedded in JSX before rendering them. Everything is converted to a string before being rendered. This helps prevent XSS (cross-site-scripting) attacks.

JSX Represents Objects

Babel compiles JSX down to React.createElement() calls.

These two examples are identical:

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

React.createElement() performs a few checks to help you write bug-free code but essentially it creates an object like this:

// Note: this structure is simplified
const element = {
  type: 'h1',
  props: {
    className: 'greeting',
    children: 'Hello, world!',
  },
};

These objects (React elements) are basically descriptions of what you want to see on the screen. React reads these objects and uses them to construct the DOM and keep it up to date.

TL;DR

  • JSX is a syntax extension for JavaScript
  • With JSX you can React easily
  • React gives you error and warning messages when using JSX

Thanks for reading and if you have any questions, use the comment function or send me a message @mariokandut. If you want to know more about React, have a look at these React Tutorials.

References (and Big thanks):

React Docs

Scroll to top ↑