Introducing JSX – React (2024)

These docs are old and won’t be updated. Go to react.dev for the new React docs.

These new documentation pages teach modern React and include live examples:

Consider this variable declaration:

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

This funny tag syntax is neither a string nor HTML.

It is called JSX, and it is a syntax extension to JavaScript. We recommend using it with React to describe what the UI should look like. JSX may remind you of a template language, but it comes with the full power of JavaScript.

JSX produces React “elements”. We will explore rendering them to the DOM in the next section. Below, you can find the basics of JSX necessary to get you started.

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.

Instead of artificially separating technologies by putting markup and logic in separate files, React separates concerns with loosely coupled units called “components” that contain both. We will come back to components in a further section, but if you’re not yet comfortable putting markup in JS, this talk might convince you otherwise.

React doesn’t require using JSX, but most people find it helpful as a visual aid when working with UI inside the JavaScript code. It also allows React to show more useful error and warning messages.

With that out of the way, let’s get started!

Embedding Expressions in JSX

In the example below, we declare a variable called name and then use it inside JSX by wrapping it in curly braces:

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

You can put any valid JavaScript expression inside the curly braces in JSX. For example, 2 + 2, user.firstName, or formatName(user) are all valid JavaScript expressions.

In the example below, we embed the result of calling a JavaScript function, formatName(user), into an <h1> element.

function formatName(user) { return user.firstName + ' ' + user.lastName;}const user = { firstName: 'Harper', lastName: 'Perez'};const element = ( <h1> Hello, {formatName(user)}! </h1>);

Try it on CodePen

We split JSX over multiple lines for readability. While it isn’t required, when doing this, we also recommend wrapping it in parentheses to avoid the pitfalls of automatic semicolon insertion.

JSX is an Expression Too

After compilation, JSX expressions become regular JavaScript function calls and evaluate to JavaScript objects.

This means that 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>;}

Specifying Attributes with JSX

You may use quotes to specify string literals as attributes:

const element = <a href="https://www.reactjs.org"> link </a>;

You may 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 when embedding a JavaScript expression in an attribute. You should either use quotes (for string values) or curly braces (for expressions), but not both in the same attribute.

Warning:

Since JSX is closer to JavaScript than to HTML, React DOM uses camelCase property naming convention instead of HTML attribute names.

For example, class becomes className in JSX, and tabindex becomes tabIndex.

Specifying Children with JSX

If a tag is empty, you may 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>);

JSX Prevents Injection Attacks

It is safe to embed user input in JSX:

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. Thus it ensures that you can never inject anything that’s not explicitly written in your application. 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 simplifiedconst element = { type: 'h1', props: { className: 'greeting', children: 'Hello, world!' }};

These objects are called “React elements”. You can think of them as 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.

We will explore rendering React elements to the DOM in the next section.

Tip:

We recommend using the “Babel” language definition for your editor of choice so that both ES6 and JSX code is properly highlighted.

Introducing JSX – React (2024)

FAQs

What is JSX in React? ›

JSX stands for JavaScript syntax extension. It is a JavaScript extension that allows us to describe React's object tree using a syntax that resembles that of an HTML template. It is just an XML-like extension that allows us to write JavaScript that looks like markup and have it returned from a component.

Why use JSX instead of JS? ›

Support for HTML-like syntax: JSX allows you to use HTML-like syntax, including tags, attributes, and self-closing tags, making it easier to describe the structure and appearance of UI components. JS does not have built-in support for HTML-like syntax.

Is JSX good for React? ›

Although there are other ways to write components, most React developers prefer the conciseness of JSX, and most codebases use it.

Is JSX mandatory for React? ›

JSX is not a requirement for using React.

Using React without JSX is especially convenient when you don't want to set up compilation in your build environment. Each JSX element is just syntactic sugar for calling React. ... So, anything you can do with JSX can also be done with just plain JavaScript.

Is JSX still used in React? ›

We will come back to components in a further section, but if you're not yet comfortable putting markup in JS, this talk might convince you otherwise. React doesn't require using JSX, but most people find it helpful as a visual aid when working with UI inside the JavaScript code.

Is JSX stricter than HTML? ›

JSX looks a lot like HTML, but it is a bit stricter and can display dynamic information. The best way to understand this is to convert some HTML markup to JSX markup.

What is the disadvantage of JSX? ›

JSX Complexity

However, some developers find JSX daunting due to its unfamiliar syntax, which may slow down the learning process. Despite its initial complexity, JSX offers advantages like improved code readability and component-based structure, fostering a more efficient development workflow.

Is JSX faster than JS? ›

JSX performs optimization while compiling the source code to JavaScript. The generated code runs faster than an equivalent code written directly in JavaScript.

When should I use JSX? ›

JSX stands for JavaScript XML, and it is a syntax extension to JavaScript that allows us to write HTML-like code in ReactJS. JSX is not a requirement for using React, but it makes it easier to create and maintain React components.

What is the advantage of JSX? ›

Benefits of Using JSX

JSX enables React to display error and warning messages, which aids in debugging. With JSX, you can write large pieces of code in a more organized and simplified manner. If you have a good understanding of HTML, you'll find it easier to use JSX when developing React applications.

What frameworks use JSX? ›

JSX is not unique to React and in fact can be used with Vue. It is also used with Solid, Preact, and other frameworks which generally out-perform React and present the developer with less foot-guns. Vue's SFC template is itself an abstraction and it's fully possible to use Vue with pure JavaScript as well.

Can a browser understand JSX? ›

JSX is not natively understood by browsers. Instead, it needs to be converted into valid JavaScript using tools like Babel. This process is known as transpilation, which ensures that browsers can properly interpret and run the JSX code embedded within React applications.

What is the point of JSX in React? ›

What is JSX? JSX stands for JavaScript XML. JSX allows us to write HTML in React. JSX makes it easier to write and add HTML in React.

Can I use JSX without importing React? ›

With the new transform, you can use JSX without importing React. Depending on your setup, its compiled output may slightly improve the bundle size.

How is JSX converted to js in React? ›

Browser does not understand JSX directly. Because it's not valid JavaScript. So, to make it browser understandable there needs a compiler/transpiler which is called Babel. You can set up your own babel configuration or use vite or create-react-app which internally uses Babel for the JSX to JavaScript conversion.

What is JSX in React and how is it different from HTML? ›

JSX and HTML differ in their integration and usage within web development. HTML is a standard markup language for creating static web pages, while JSX is a syntax extension for JavaScript, mainly used with React, allowing HTML-like code within JavaScript.

What is JSX and Babel in React? ›

We use Babel with React to transpile the JSX code into simple React functions that can be understood by browsers. Using this way we can assure that our JSX code can work in almost any browser. This combination is widely used in modern-day web development.

How to run a JSX file? ›

Let's start by running our first JSX program: hello. jsx . We use the jsx command, which is the JSX compiler in the JSX distribution, to compile JSX source code to JavaScript. Now you can run a JSX program with the following command and you will get Hello, world on the console.

What is JSX type? ›

JSX. Element is a type alias for a JSX element. JSX is a syntax extension for JavaScript that allows you to write HTML-like code in your JavaScript files. It is a way of representing the structure of a user interface in the form of a tree of nested elements, with each element representing a component.

Top Articles
Coca-Cola (KO) Stock Forecast and Price Target 2024
Where to get a $50,000 loan
Katie Pavlich Bikini Photos
Gamevault Agent
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Free Atm For Emerald Card Near Me
Craigslist Mexico Cancun
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Doby's Funeral Home Obituaries
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Select Truck Greensboro
Things To Do In Atlanta Tomorrow Night
Non Sequitur
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Craigslist In Flagstaff
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Testberichte zu E-Bikes & Fahrrädern von PROPHETE.
Aaa Saugus Ma Appointment
Geometry Review Quiz 5 Answer Key
Walgreens Alma School And Dynamite
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Pixel Combat Unblocked
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Rogold Extension
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Facebook Marketplace Marrero La
Nobodyhome.tv Reddit
Topos De Bolos Engraçados
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hampton In And Suites Near Me
Stoughton Commuter Rail Schedule
Bedbathandbeyond Flemington Nj
Free Carnival-themed Google Slides & PowerPoint templates
Otter Bustr
Selly Medaline
Latest Posts
Article information

Author: Catherine Tremblay

Last Updated:

Views: 5831

Rating: 4.7 / 5 (67 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Catherine Tremblay

Birthday: 1999-09-23

Address: Suite 461 73643 Sherril Loaf, Dickinsonland, AZ 47941-2379

Phone: +2678139151039

Job: International Administration Supervisor

Hobby: Dowsing, Snowboarding, Rowing, Beekeeping, Calligraphy, Shooting, Air sports

Introduction: My name is Catherine Tremblay, I am a precious, perfect, tasty, enthusiastic, inexpensive, vast, kind person who loves writing and wants to share my knowledge and understanding with you.