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
Shop for title insurance and other closing services | Consumer Financial Protection Bureau
How to Save for a Down Payment on a Home and Fund a Roth IRA
Spectrum Gdvr-2007
Rubratings Tampa
Zabor Funeral Home Inc
فیلم رهگیر دوبله فارسی بدون سانسور نماشا
Fat Hog Prices Today
Geodis Logistic Joliet/Topco
Ribbit Woodbine
Cinepacks.store
Tabler Oklahoma
Best Restaurants In Seaside Heights Nj
Pro Groom Prices – The Pet Centre
Cooktopcove Com
Ivegore Machete Mutolation
Wgu Admissions Login
The Murdoch succession drama kicks off this week. Here's everything you need to know
Justified Official Series Trailer
Overton Funeral Home Waterloo Iowa
Alfie Liebel
Www.craigslist.com Savannah Ga
Conscious Cloud Dispensary Photos
Hdmovie2 Sbs
Lines Ac And Rs Can Best Be Described As
Piri Leaked
Impact-Messung für bessere Ergebnisse « impact investing magazin
Dashboard Unt
Mcclendon's Near Me
Craigslist Comes Clean: No More 'Adult Services,' Ever
Pokemon Inflamed Red Cheats
Guinness World Record For Longest Imessage
Srjc.book Store
Housing Intranet Unt
49S Results Coral
Fedex Walgreens Pickup Times
Worlds Hardest Game Tyrone
The Pretty Kitty Tanglewood
Rise Meadville Reviews
Tamilyogi Ponniyin Selvan
A Man Called Otto Showtimes Near Amc Muncie 12
Pawn Shop Open Now
Rochester Ny Missed Connections
Lovely Nails Prices (2024) – Salon Rates
Pulitzer And Tony Winning Play About A Mathematical Genius Crossword
Sechrest Davis Funeral Home High Point Nc
'The Nun II' Ending Explained: Does the Immortal Valak Die This Time?
Top 1,000 Girl Names for Your Baby Girl in 2024 | Pampers
Plumfund Reviews
Walmart Front Door Wreaths
Worlds Hardest Game Tyrone
Loss Payee And Lienholder Addresses And Contact Information Updated Daily Free List Bank Of America
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.