Writing Markup with JSX – React (2024)

JSX is a syntax extension for JavaScript that lets you write HTML-like markup inside a JavaScript file. Although there are other ways to write components, most React developers prefer the conciseness of JSX, and most codebases use it.

You will learn

  • Why React mixes markup with rendering logic
  • How JSX is different from HTML
  • How to display information with JSX

JSX: Putting markup into JavaScript

The Web has been built on HTML, CSS, and JavaScript. For many years, web developers kept content in HTML, design in CSS, and logic in JavaScript—often in separate files! Content was marked up inside HTML while the page’s logic lived separately in JavaScript:

Writing Markup with JSX – React (1)

Writing Markup with JSX – React (2)

Writing Markup with JSX – React (3)

Writing Markup with JSX – React (4)

But as the Web became more interactive, logic increasingly determined content. JavaScript was in charge of the HTML! This is why in React, rendering logic and markup live together in the same place—components.

Writing Markup with JSX – React (5)

Writing Markup with JSX – React (6)

Writing Markup with JSX – React (7)

Writing Markup with JSX – React (8)

Keeping a button’s rendering logic and markup together ensures that they stay in sync with each other on every edit. Conversely, details that are unrelated, such as the button’s markup and a sidebar’s markup, are isolated from each other, making it safer to change either of them on their own.

Each React component is a JavaScript function that may contain some markup that React renders into the browser. React components use a syntax extension called JSX to represent that markup. 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.

Note

JSX and React are two separate things. They’re often used together, but you can use them independently of each other. JSX is a syntax extension, while React is a JavaScript library.

Converting HTML to JSX

Suppose that you have some (perfectly valid) HTML:

<h1>Hedy Lamarr's Todos</h1>

<img

src="https://i.imgur.com/yXOvdOSs.jpg"

alt="Hedy Lamarr"

class="photo"

>

<ul>

<li>Invent new traffic lights

<li>Rehearse a movie scene

<li>Improve the spectrum technology

</ul>

And you want to put it into your component:

export default function TodoList() {

return (

// ???

)

}

If you copy and paste it as is, it will not work:

This is because JSX is stricter and has a few more rules than HTML! If you read the error messages above, they’ll guide you to fix the markup, or you can follow the guide below.

Note

Most of the time, React’s on-screen error messages will help you find where the problem is. Give them a read if you get stuck!

The Rules of JSX

1. Return a single root element

To return multiple elements from a component, wrap them with a single parent tag.

For example, you can use a <div>:

<div>

<h1>Hedy Lamarr's Todos</h1>

<img

src="https://i.imgur.com/yXOvdOSs.jpg"

alt="Hedy Lamarr"

class="photo"

>

<ul>

...

</ul>

</div>

If you don’t want to add an extra <div> to your markup, you can write <> and </> instead:

<>

<h1>Hedy Lamarr's Todos</h1>

<img

src="https://i.imgur.com/yXOvdOSs.jpg"

alt="Hedy Lamarr"

class="photo"

>

<ul>

...

</ul>

</>

This empty tag is called a Fragment. Fragments let you group things without leaving any trace in the browser HTML tree.

Deep Dive

Why do multiple JSX tags need to be wrapped?

JSX looks like HTML, but under the hood it is transformed into plain JavaScript objects. You can’t return two objects from a function without wrapping them into an array. This explains why you also can’t return two JSX tags without wrapping them into another tag or a Fragment.

2. Close all the tags

JSX requires tags to be explicitly closed: self-closing tags like <img> must become <img />, and wrapping tags like <li>oranges must be written as <li>oranges</li>.

This is how Hedy Lamarr’s image and list items look closed:

<>

<img

src="https://i.imgur.com/yXOvdOSs.jpg"

alt="Hedy Lamarr"

class="photo"

/>

<ul>

<li>Invent new traffic lights</li>

<li>Rehearse a movie scene</li>

<li>Improve the spectrum technology</li>

</ul>

</>

3. camelCase all most of the things!

JSX turns into JavaScript and attributes written in JSX become keys of JavaScript objects. In your own components, you will often want to read those attributes into variables. But JavaScript has limitations on variable names. For example, their names can’t contain dashes or be reserved words like class.

This is why, in React, many HTML and SVG attributes are written in camelCase. For example, instead of stroke-width you use strokeWidth. Since class is a reserved word, in React you write className instead, named after the corresponding DOM property:

<img

src="https://i.imgur.com/yXOvdOSs.jpg"

alt="Hedy Lamarr"

className="photo"

/>

You can find all these attributes in the list of DOM component props. If you get one wrong, don’t worry—React will print a message with a possible correction to the browser console.

Pitfall

For historical reasons, aria-* and data-* attributes are written as in HTML with dashes.

Pro-tip: Use a JSX Converter

Converting all these attributes in existing markup can be tedious! We recommend using a converter to translate your existing HTML and SVG to JSX. Converters are very useful in practice, but it’s still worth understanding what is going on so that you can comfortably write JSX on your own.

Here is your final result:

Recap

Now you know why JSX exists and how to use it in components:

  • React components group rendering logic together with markup because they are related.
  • JSX is similar to HTML, with a few differences. You can use a converter if you need to.
  • Error messages will often point you in the right direction to fixing your markup.
Writing Markup with JSX – React (2024)

FAQs

What is the benefit of writing Reactjs code with JSX? ›

Some benefits of using JSX in React development include: Readability: JSX code is often more readable, especially for those familiar with HTML. Performance: JSX compiles down to optimized JavaScript functions, ensuring faster rendering.

Is JSX a markup language? ›

JSX is a syntax extension for JavaScript that lets you write HTML-like markup inside a JavaScript file. Although there are other ways to write components, most React developers prefer the conciseness of JSX, and most codebases use it.

Is JSX necessary to work with 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.

What is markup in JSX? ›

More commonly referred to as “JSX,” JavaScript XML is a form of markup that allows us to write HTML in React by converting HTML tags into React elements. Utilizing JSX allows us to write HTML elements in JavaScript, which is then rendered to the DOM.

Is it better to use JSX? ›

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.

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.

Is JSX better than HTML? ›

Unlike HTML, JSX enables the embedding of JavaScript expressions and facilitates the creation of reusable components, promoting a more dynamic and efficient approach to web development.

Is JSX just syntactic sugar? ›

JSX is just one-to-one syntactic sugar for a createElement call (https://react.dev/reference/react/createElement). You don't even need to use it with React, any library that defines an identical function interface will do. Used to be, but you are right that JSX is a rather thin syntax over function calls.

Is HTMx better than React? ›

HTMX: Easier to maintain for smaller projects with less client-side logic. Adding or changing interactivity involves minimal changes to the existing codebase. React: More suitable for large-scale applications with complex UIs.

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 React enough for a job? ›

React developers are needed across geographies and industries. However, in order to be successful in your career, you will need to do more than just learning React JS skills.

Can you write JSX without React? ›

Even though JSX had been around before React, it wouldn't have been nearly as popular without React picking it up. However, we can actually use JSX without React, and it's not that difficult either. The way React works is by configuring your bundler to convert JSX into calls to a createElement function.

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 difference between markup and scripting? ›

A markup language is something like HTML or CSS which doesn't contain any actual program code (routines, loops) as such. Scripting languages generally automate or extend tasks which could usually be done manually. They're frequently embedded inside applications, such as VBSCRIPT which is part of MS Office.

What is the difference between markup and annotation? ›

What to know. Annotations inside of PDFs are split into 2 groups: markup annotations and non-markup annotations. Markup annotations are primarily used to mark up the content of a PDF document. Non-markup annotations are used for other purposes, including interactive forms and multimedia.

What is the significance of JSX? ›

JSX looks like HTML, a language used for structuring and presenting content on the web, but it has the full power of JavaScript. It allows developers to write HTML-like code in their JavaScript, making the code easier to understand and maintain. One of the key aspects of JSX is its ability to produce React "elements".

Why JSX is better than HTML? ›

Unlike HTML, JSX enables the embedding of JavaScript expressions and facilitates the creation of reusable components, promoting a more dynamic and efficient approach to web development.

What are the benefits of using TypeScript with ReactJS? ›

Top 10 reasons why to use TypeScript with React
  • Improved IDE support. TypeScript works with various code editors like Visual Studio Code, Atom, and Sublime Text. ...
  • Code documentation. ...
  • Easier collaboration. ...
  • Better error handling. ...
  • Improved scalability. ...
  • Better performance. ...
  • Reduced maintenance costs. ...
  • Easier refactoring.
May 9, 2024

Why do we write our React Native code in JSX? ›

This is JSX - a syntax for embedding XML within JavaScript. Many frameworks use a specialized templating language which lets you embed code inside markup language. In React, this is reversed. JSX lets you write your markup language inside code.

Top Articles
Jesuit Resource - Martin Luther King Jr. Quotes
7 Halal Stock Screening Methodologies You Need to Know - Musaffa Academy
Housing near Juneau, WI - craigslist
Couchtuner The Office
oklahoma city for sale "new tulsa" - craigslist
Volstate Portal
Derpixon Kemono
Ohiohealth Esource Employee Login
What is a basic financial statement?
Weekly Math Review Q4 3
Nexus Crossword Puzzle Solver
Edible Arrangements Keller
Things To Do In Atlanta Tomorrow Night
Bestellung Ahrefs
SXSW Film & TV Alumni Releases – July & August 2024
R Cwbt
Divina Rapsing
All Obituaries | Buie's Funeral Home | Raeford NC funeral home and cremation
Aldine Isd Pay Scale 23-24
Officialmilarosee
Noaa Ilx
Vandymania Com Forums
Joann Ally Employee Portal
Gopher Hockey Forum
Hermitcraft Texture Pack
Promiseb Discontinued
Shreveport City Warrants Lookup
Cookie Clicker Advanced Method Unblocked
Dei Ebill
Star Wars Armada Wikia
The Collective - Upscale Downtown Milwaukee Hair Salon
Things to do in Pearl City: Honolulu, HI Travel Guide by 10Best
Miles City Montana Craigslist
Wheeling Matinee Results
Sam's Club Near Wisconsin Dells
Swgoh Boba Fett Counter
Shnvme Com
Quake Awakening Fragments
Austin Automotive Buda
Michael Jordan: A timeline of the NBA legend
MSD Animal Health Hub: Nobivac® Rabies Q & A
Craigslist Putnam Valley Ny
Husker Football
The Complete Uber Eats Delivery Driver Guide:
Value Village Silver Spring Photos
News & Events | Pi Recordings
5103 Liberty Ave, North Bergen, NJ 07047 - MLS 240018284 - Coldwell Banker
Clock Batteries Perhaps Crossword Clue
Motorcycle For Sale In Deep East Texas By Owner
Gummy Bear Hoco Proposal
Campaign Blacksmith Bench
Latest Posts
Article information

Author: Prof. An Powlowski

Last Updated:

Views: 5848

Rating: 4.3 / 5 (64 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Prof. An Powlowski

Birthday: 1992-09-29

Address: Apt. 994 8891 Orval Hill, Brittnyburgh, AZ 41023-0398

Phone: +26417467956738

Job: District Marketing Strategist

Hobby: Embroidery, Bodybuilding, Motor sports, Amateur radio, Wood carving, Whittling, Air sports

Introduction: My name is Prof. An Powlowski, I am a charming, helpful, attractive, good, graceful, thoughtful, vast person who loves writing and wants to share my knowledge and understanding with you.