ReactJS - JSX (2024)

As we learned earlier, React JSX is an extension to JavaScript. It allows writing a JavaScript code that looks like an HTML code. For instance, consider the following code:

const element = <h1>Hello React!</h1>

The tag provided in the code above is known as JSX. JSX is mainly used to provide information about the appearance of an interface. However, it is not completely a template language but a syntax extension to JavaScript. JSX produces elements that are rendered into a DOM, in order to specify what the output must look like.

Using JSX in ReactJS

JSX enables the developer to create a virtual DOM using XML syntax. It compiles down to pure JavaScript (React.createElement function calls), therefore, it can be used inside any valid JavaScript code.

  • Assign to a variable.
var greeting = <h1>Hello React!</h1>
  • Assign to a variable based on a condition.
var canGreet = true; if(canGreet) { greeting = <h1>Hello React!</h1> }
  • Can be used as return value of a function.
function Greeting() { return <h1>Hello React!</h1> } greeting = Greeting()
  • Can be used as argument of a function.
function Greet(message) { ReactDOM.render(message, document.getElementById('react-app') } Greet(<h1>Hello React!</h1>)

Why JSX?

Using JSX with React is not mandatory, as there are various options to achieve the same thing as JSX; but it is helpful as a visual aid while working with UI inside a JavaScript code.

  • JSX performs optimization while translating the code to JavaScript, making it faster than regular JavaScript.

  • React uses components that contain both markup and logic in a single file, instead of separate files.

  • Most of the errors can be found at compilation time, as the data flow is unidirectional.

  • Creating templates becomes easier with JSX.

  • We can use JSX inside of conditional statements (if−else) and loop statements (for loops), can assign it to variables, accept it as arguments, or return it from functions.

  • Using JSX can prevent Cross Site Scripting attacks, or injection attacks.

Expressions in JSX

JSX supports expression in pure JavaScript syntax. Expression has to be enclosed inside the curly braces, { }. Expression can contain all variables available in the context, where the JSX is defined. Let us create simple JSX with expression.

Example

<script type="text/babel"> var cTime = new Date().toTimeString(); ReactDOM.render( <div><p>The current time is {cTime}</p></div>, document.getElementById('react-app') );</script>

Output

Here, cTime used in the JSX using expression. The output of the above code is as follows,

The Current time is 21:19:56 GMT+0530(India Standard Time)

One of the positive side effects of using expression in JSX is that it prevents Injection attacks as it converts any string into html safe string.

Functions in JSX

JSX supports user defined JavaScript function. Function usage is similar to expression. Let us create a simple function and use it inside JSX.

Example

<script type="text/babel"> var cTime = new Date().toTimeString(); ReactDOM.render( <div><p>The current time is {cTime}</p></div>, document.getElementById('react-app') );</script>

Output

Here, getCurrentTime() is used get the current time and the output is similar as specified below −

The Current time is 21:19:56 GMT+0530(India Standard Time)

Attributes in JSX

JSX supports HTML like attributes. All HTML tags and its attributes are supported. Attributes has to be specified using camelCase convention (and it follows JavaScript DOM API) instead of normal HTML attribute name. For example, class attribute in HTML has to be defined as className. The following are few other examples −

  • htmlFor instead of for
  • tabIndex instead of tabindex
  • onClick instead of onclick

Example

<style> .red { color: red }</style><script type="text/babel"> function getCurrentTime() { return new Date().toTimeString(); } ReactDOM.render( <div> <p>The current time is <span className="red">{getCurrentTime()}</span></p> </div>, document.getElementById('react-app') );</script>

Output

The output is as follows −

The Current time is 22:36:55 GMT+0530(India Standard Time)

Using Expression within Attributes

JSX supports expression to be specified inside the attributes. In attributes, double quote should not be used along with expression. Either expression or string using double quote has to be used. The above example can be changed to use expression in attributes.

<style> .red { color: red }</style><script type="text/babel"> function getCurrentTime() { return new Date().toTimeString(); } var class_name = "red"; ReactDOM.render( <div> <p>The current time is <span className={class_name}>{getCurrentTime()}</span></p> </div>, document.getElementById('react-app') );</script>

Nested Elements in JSX

Nested elements in JSX can be used as JSX Children. They are very useful while displaying the nested components. You can use any type of elements together including tags, literals, functions, expressions etc. But false, null, undefined, and true are all valid elements of JSX; they just don't render as these JSX expressions will all render to the same thing. In this case, JSX is similar to HTML.

Following is a simple code to show the usage of nested elements in JSX −

<div> This is a list: <ul> <li>Element 1</li> <li>Element 2</li> </ul></div>

Advertisem*nts

ReactJS - JSX (2024)
Top Articles
Managing FOMO (Fear of Missing Out) in Forex Trading
Time and Frequency from A to Z, G
Ceton Village Diggy
Everything Candace Owens Gets Wrong in Episode 1 of “A Shot in the Dark”
Gabrielle Abbate Obituary
Westcare Clinic Renton
Best Sorc Leveling Build
Funeral Homes in Grand Forks, North Dakota
Missed Connections Inland Empire
Stretchmark Camouflage Highland Park
Don Misael Tamales Menu
Tj Maxx Sugarhouse
Lt4200 Huskee Manual
Ba Atm Near Me
How Did Kratos Remove The Chains
Danielle Moodie-Mills Net Worth
385-437-2602
Getting Started With Python IDLE – Real Python
A Far Eastern Yarn Ffxiv
Jesus Blessed Savior He's Worthy To Be Praised Lyrics
Boyfriend (2018) | KDrama Recaps on Dramabeans
New Jersey Cash Pop
Digoxin Ati Medication Template
Used Chest Freezer For Sale Craigslist
Swgoh Darth Malgus
Great Clips Grandview Station Marion Reviews
Translations Of Linear Functions Worksheet Answer Key
Munis Self Service Cumberland County
John W Creasy Died December 16 2003
Cash App Paid Screenshot
Company doctor or health and safety service
Craigslist Malone New York
T188 Pill
Uh Board Of Regents Meeting
I Bought Udental Pro: Here's My Honest Review About This Automatic Toothbrush! -
NRA Training
Duda Nowak Reddit
Sauna Konfigurator - Ihr Weg zur Entspannung | Wellness4Me
Scholastic Toolkit Sign In
How To Add Friends On Regal App
Kourend & Kebos Diary | OSRS Toolkit
Juicy Deal D-Art
Wicked Local Plymouth Police Log 2022
Cvs Newr.me
Facility Scheduler Hca North Florida
12 Rue Gotlib 21St Arrondissem*nt
Mission Impossible 7 Showtimes Near Regal Bridgeport Village
Snohomish Hairmasters
Baldurs Gate 3: Komplettlösung, Guides, Tipps und Tricks
Latest Posts
Article information

Author: Merrill Bechtelar CPA

Last Updated:

Views: 5810

Rating: 5 / 5 (70 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Merrill Bechtelar CPA

Birthday: 1996-05-19

Address: Apt. 114 873 White Lodge, Libbyfurt, CA 93006

Phone: +5983010455207

Job: Legacy Representative

Hobby: Blacksmithing, Urban exploration, Sudoku, Slacklining, Creative writing, Community, Letterboxing

Introduction: My name is Merrill Bechtelar CPA, I am a clean, agreeable, glorious, magnificent, witty, enchanting, comfortable person who loves writing and wants to share my knowledge and understanding with you.