JSX in React - Explained with examples (2023)

/ #React
JSX in React - Explained with examples (1)
Yogesh Chavan
JSX in React - Explained with examples (2)

JSX is one of the core concepts of React. So if you get it right, you can write better React code.

In this article we will examine:

  • What is JSX in React and how to use it?
  • How JSX becomesreact.createItem
  • What is a JSX expression and what can we write in it?
  • Common problems in JSX

And much more. So let's start.

What is JSX?

JSX is a JavaScript extension syntax used in React to easily write HTML and JavaScript together.

Look at the following code:

const jsx = <h1>This is JSX</h1>

This is simple JSX code in React. But the browser doesn't understand this JSX because it's not valid JavaScript code. That's because we're assigning an HTML tag to a variable, which isn't a string, just HTML code.

Then to turn it into browser-readable JavaScript code, we use a tool likebabelthis is a JavaScript compiler/transpiler.

You can define your own babel configuration using the webpack as I show inThis article. or you can useCreate React Applicationwhich is used internally by Babel to convert JSX to JavaScript.

We can use the above JSX in our React code like this:

class JSXDemo extends React.Component { render() { return <h1>This is JSX</h1>; }}ReactDOM.render(<JSXDemo />, document.getElementById('root'));

Here we send out the JSXJSX-Democomponent and render it with the onscreenReactDOM.processMethod.

Here is oneCode-Sandbox-Demo.

When Babel runs the above JSX, it converts it to the following code:

class JSXDemo Extension React.Component { render() { return React.createElement("h1", null, "Is JSX"); }}

Here is oneCode-Sandbox-Demo.

As you can see in the code sandbox above, the code still correctly renders the content to the screenreact.createItem.

This was the old way of writing code in React, but it's a pain to writereact.createItemalways, even to add a simple div.

Then React introduced the JSX method of writing code, which makes the code easy to write and understand.

Learn how to convert JSX toreact.createItemis very important as a React developer (also a popular interview question).

What is the React.createElement function?

Any JSX will be converted toreact.createItemFunction call that the browser understands.

Himreact.createItemhas the following syntax:

React.createElement(type, [props], [...children])

Let's look at the parameters ofcreateElementProfession.

  • he writesit can be an HTML tag like h1, div or a React component
  • accesoriesare the attributes that the element should have
  • Kindercontain other HTML tags or be a component

Himreact.createItemThe call is also converted to the object representation as follows:

{ type: 'h1', props: { children: 'This is JSX' }}

You can see this object representation if you assign JSX to a local variable and register it like this:

class JSXDemo extends React.Component { render() { const jsx = <h1>This is JSX</h1>; Console.log (jsx); return jsx; }}ReactDOM.render(<JSXDemo />, document.getElementById('root'));

Here is oneCode-Sandbox-Demo.

The log will be printed as shown below:

JSX in React - Explained with examples (3)

Now look at the following code:

class JSXDemo extends React.Component { render() { const jsx = <h1 id="jsx">This is JSX</h1>; Console.log (jsx); return jsx; }}ReactDOM.render(<JSXDemo />, document.getElementById("root"));

Here we use JSX as follows:

<h1 id="jsx">This is JSX</h1>

Then React converts this JSX into the following code:

React.createElement("h1", { id: "jsx" }, "Das ist JSX");

If attributes are added to the HTML tag, as in our case, these are passed to the as the second parameterreact.createItemassociate. The representation of the object looks like this:

{ type: 'h1', props: { id: 'jsx', children: 'Das ist JSX' } }

Here is oneCode-Sandbox-Demo.

The log will be printed as shown below:

JSX in React - Explained with examples (4)

Now let's add some complexity to JSX to see how to convert it to JSX.react.createItemassociate.

class JSXDemo estende React.Component { handleOnClick = () => { console.log("clicked"); }; render() { return ( <button id="btn" onClick={this.handleOnClick}> Clique aqui </button> ); }}ReactDOM.render(<JSXDemo />, document.getElementById("root"));

Here we addwhen clickedController for the button.

For the code above, thereact.createItemthe call looks like this:

React.createElement("button", { id: "btn", onClick: function() {}}, "Clique aqui")

Here is oneCode-Sandbox-Demo.

The representation of the object looks like this:

JSX in React - Explained with examples (5)

So, from all the examples above, it is clear that JSX is becoming onereact.createItemcall and is then converted to its object representation.

If you want to see the JSX forreact.createItemConversion code you can navigate toThis applicationwhat i believedThis article. There you can write the JSX code on the left and see the converted code on the right as shown below:

JSX in React - Explained with examples (6)

How to return complex JSX

Look at the following code:

import React from "react"; import ReactDOM from "react-dom"; const App = () => { return ( <p>¡This is the first JSX element!</p> <p>This is another JSX element</p > );};const rootElement = document.getElementById ("root");ReactDOM.render(<App />, rootElement);

Here is oneCode-Sandbox-Demo.

Here we are returning two paragraphs from the application component. But when you run the code you get this error:

JSX in React - Explained with examples (7)

We're getting an error because React requires neighboring elements to be wrapped in a parent tag.

As we saw,<p>This is the first JSX element!</p>becomes pureReact.createElement("p", null, "This is the first JSX element!")j<p>This is another JSX element</p>becomes pureReact.createElement("p", null, "This is another JSX element").

The converted code looks like this:

import react from react; import ReactDOM from "react-dom"; const App = () => { return ( React.createElement("p", null, "This is the first JSX element!"); React.createElement( "p", null, "This is the other JSX element ") ; );};const rootElement = document.getElementById("root");ReactDOM.render(<App />, rootElement);

Here we sweep out two thingsAppComponent that will not work as there is no parent to group the two together.

To make it work, the obvious solution is to wrap both in a parent, probably oneclassificationI like this:

import React from „react“; import ReactDOM from „react-dom“; const App = () => { return ( <div> <p>¡Es ist das erste Element von JSX!</p> <p>Es ist anders elemento JSX </p> </div> );};const rootElement = document.getElementById("root");ReactDOM.render(<App />, rootElement);

Here is oneCode-Sandbox-Demo.

But there are other ways to get it working.

First you can try to return it as an array like this:

import React from "react"; import ReactDOM from "react-dom"; const App = () => { return ( [<p>This is the first JSX element!</p>,<p>This is another JSX element </p>] );};const rootElement = document .getElementById("root");ReactDOM.render(<App />, rootElement);

Here is oneCode-Sandbox-Demo.

This will do the job but as you can see in the browser console you will get a warningWarning: Each child in a collection must have a unique "key" accessory.

Because in React, a unique key needs to be added to each element in the array (when rendering with JSX).

We can fix it by adding a unique key to adjacent elements:

import react from react; import ReactDOM from "react-dom"; const App = () => { return ( [<p key="first">This is the first JSX element!</p>,<p key="second">This is another JSX element</p >] ) ;};const rootItem = document.getItemById("root");ReactDOM.render(<App/>, rootItem);

Here is oneCode-Sandbox-Demo.

The other way to fix it is to usereact.fragmentComponents:

import React from "react"; import ReactDOM from "react-dom"; const App = () => { return ( <React.Fragment> <p>This is the first JSX element!</p> <p>This is another JSX element</p> </React.Fragment> );};const rootElement = document.getElementById("root");ReactDOM.render(<App />, rootElement);

Here is oneCode-Sandbox-Demo.

react.fragmentwas added in React version 16.2 because we always need to wrap multiple contiguous elements in a tag (like div) within each JSX returned from a component. However, this adds unnecessary div tags.

That's fine most of the time, but there are certain cases where it's not good.

For example, when we use flexbox, there is a special parent-child relationship in the flexbox framework. And adding divs in the middle makes it difficult to keep the layout you want.

then usereact.fragmentsolve this problem.

Scrapsyou can group a list of children without adding additional nodes to the DOM.

If you have a line of code like this:

<p>This is text</p>

and you want to add a comment to this code, you need to enclose this code in the JSX expression syntax inside of/*j*/Comment icons like this:

{/* <p>This is text</p> */}

Addendum:Instead of writing the comment manually, you can usecommand + /(Mac) etc.control +/Keyboard shortcuts to add or delete the comment.

How to add JavaScript code in JSX

Up to this point we have only used HTML tags as part of JSX. But JSX becomes more useful when we add JavaScript code in it.

To add JavaScript code in JSX, we need to enclose it in curly brackets like this:

const = application () => { const number = 10; return ( <div> <p>Nummer: {number}</p> </div>);};

Here is oneCode-Sandbox-Demo.

Within the square brackets, we can simply write an expression that evaluates to a specific value.

Therefore, this bracket syntax is often referred to as JSX expression syntax.

The following are valid things you can have in a JSX expression:

  • A string like "hello"
  • A number like 10
  • An array like [1, 2, 4, 5]
  • An object property that evaluates to a specific value
  • A function call that returns a value that can be JSX
  • A Map method that always returns a new array
  • JSX them yes

The following things are invalid and cannot be used in a JSX expression:

  • A For or While loop or another loop
  • A variable declaration
  • A function declaration
  • A condition if
  • An object

We can write arrays in JSX expressions because<p>{[1, 2, 3, 4]}</p>will finally<p>{1}{2}{3}{4}</p>when rendering (which can be rendered with no problem).

With an object, it is not clear how the object should be represented. For example, should they be comma separated key values ​​or should they be displayed as JSON? So you will get an error if you try to display the object in a JSX expression. But we can use the object's properties instead.

Also note that undefined, null and boolean are not displayed in the UI when used in JSX.

So if you have a boolean value and you want to display it in the UI, you need to enclose it in an ES6 template literal syntax like this:

app const = () => {const isAdmin = true; return ( <div> <p>isAdmin es {`${isAdmin}`} </p> </div>);};

Here is oneCode-Sandbox-Demo.

Conditional operators in JSX expressions

we can't writeif the conditionsin JSX expressions, which can be seen as a problem. But React allows us to write conditional operators like ternary operators as well as the logical short-circuit operator && like this:

<p>{a > b ? "Bigger" : "Smaller"}</p><p>{should show && "Show"}</p>

Here is oneCode-Sandbox-DemoDescription of different ways to write JSX expressions.

How to nest JSX expressions

You can even nest JSX expressions like this:

const = application () => { const number = 10; return ( <div> {number > 0 ? ( <p>number {number} is positive</p> ) : ( <p>number {number} is negative</p> )} </div> ); };

Here is oneCode-Sandbox-Demo.

How to add a class in JSX

For example, we can add attributes to JSX elementsI WOULD GOjClass, the same as in HTML.

import react from react; import ReactDOM from "react-dom"; const App = () => { const id = "some-id"; return ( <div> <h1 id={id}>This is a header</h1> <h2 className="active">This is another header</h2> </div> );};const rootElement = document . getElementById("root");ReactDOM.render(<App />, rootElement);

Here is oneCode-Sandbox-Demo.

Note that we need to use in Reactclass namerather thanClass.

That's because if you useClassrather thanclass name, you will get a warning in the console as shown below:

JSX in React - Explained with examples (8)

Here is oneCode-Sandbox-Demo.

To understand why the warning is displayed, print out the object representation and you will see:

JSX in React - Explained with examples (9)

Here is oneCode-Sandbox-Demo.

As you can see, the Props object has theClassproperty with valueattachment. But in JavaScript,Classis a reserved word, so go for itAccessories.Classwill result in an error.

That's why React decided to use itclass namerather thanClass.

This use ofclass namerather thanClassis a common question in React interviews.

Note that in React, all attribute names are written in camelCase.

You can find the entire list of changed and unchanged attributeson here.

Conclusion

In this article, we saw how to use JSX in React. Here are some important tips:

  • Each JSX tag willreact.createItemCall and its object representation.
  • JSX expressions written in square brackets only allow things that evaluate to a specific value like string, number, array allocation method, etc.
  • In React we need to useclass namerather thanClassto add classes to the HTML element
  • All attribute names in React are written in camelCase.
  • Not defined,Null, SheBoleanoThey are not shown in the UI when used in JSX.

Thank you for reading!

check out my freeIntroduction to the React routerCourse.

Check out mine tooMaster modern JavaScriptbook to learn in detail all the latest ES6+ features to improve JavaScript and React.

Subscribe to meweekly paperJoin 1000+ subscribers to get great tips, tricks, articles and discount offers straight to your inbox.

NOTICE

NOTICE

NOTICE

NOTICE

NOTICE

NOTICE

NOTICE

NOTICE

NOTICE

NOTICE

NOTICE

NOTICE

JSX in React - Explained with examples (10)
Yogesh Chavan

Technical Writer | Freelance and Full Stack Developer | javascript | react | Node.js https://dev.to/myogeshchavan97

If you've read this far, tweet the author to show you care.

Learn to program for free. freeCodeCamp's open-source curriculum has helped over 40,000 people find developer jobs.Begin

NOTICE

Top Articles
Latest Posts
Article information

Author: The Hon. Margery Christiansen

Last Updated: 03/26/2023

Views: 5592

Rating: 5 / 5 (70 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: The Hon. Margery Christiansen

Birthday: 2000-07-07

Address: 5050 Breitenberg Knoll, New Robert, MI 45409

Phone: +2556892639372

Job: Investor Mining Engineer

Hobby: Sketching, Cosplaying, Glassblowing, Genealogy, Crocheting, Archery, Skateboarding

Introduction: My name is The Hon. Margery Christiansen, I am a bright, adorable, precious, inexpensive, gorgeous, comfortable, happy person who loves writing and wants to share my knowledge and understanding with you.