DEV Community


JSX Basics for Beginners

aravsanj profile image Aravind Sanjeev Updated on ・5 min read

Alt Text
In the previous two posts in this series, we have talked in-depth about how a React application works and how to create one. We have stated that a React application is actually written in JSX. Each component in React returns JSX which is then converted to browser-understandable regular JavaScript by a compiler. So as the third post in this series, I would like to talk about JSX -the language of React.

If you're new to ReactJS, I recommend you read the first two posts before reading this.

So, the best way to understand JSX and why it exists is to understand how we would have used React without it.

Without JSX, ReactJS will have to be written in JavaScript. When your were writing JavaScript inside HTML, you could use the <script></script> tag.

But when you are writing JavaScript and have to write HTML in between, you have no option but to use a JS function to create an HTML element.

That functions is the React.createElement() method.

For example, I want to create an h1 heading saying Hello World. In normal HTML, I would just write:

<h1>Hello World</h1>
Enter fullscreen mode Exit fullscreen mode

But if we have to do the same using JavaScript, then we will have to do it like:

React.createElement("h1", null, "Hello World");
Enter fullscreen mode Exit fullscreen mode

The first value, as we can already see is the HTML element h1 itself. The last value is the content inside the HTML tags.

In the middle, I have given a null value. That's because our HTML element does not have any attributes. Let's add attributes and see again. This time our code is:

<h1 id="first">Hello World</h1>
Enter fullscreen mode Exit fullscreen mode

If you want the same to be remade using JavaScript, you will have to write:

React.createElement("h1", {
  id: "first"
}, "Hello World");
Enter fullscreen mode Exit fullscreen mode

We can see that { id: "first" } has been added as the second value. You must have noticed how the second value has {} around it. That's because an HTML element can accept multiple attributes. So you need to separate them with a comma inside the curly braces {}. Let's add more attributes to the same HTML element.

<h1 id="first" type="text" random="random">Hello World</h1>
Enter fullscreen mode Exit fullscreen mode

The JavaScript alternative of the same statement is:

React.createElement("h1", {
  id: "first",
  type: "text",
  random: "random"
}, "Hello World");
Enter fullscreen mode Exit fullscreen mode

Now we can see that a simple HTML element has become so complex to create. This is why JSX is very important and the standard for writing apps in React.

If you wish to try this out yourself, feel free to visit this link. In the left box, type regular HTML, and on the right, it will display the JavaScript alternative. By the way, it is the same babel compiler/transpiler we use to convert the normal HTML we write using JSX into JavaScript in React.

Why you cannot use class as an attribute

You see that when we were giving attributes to the HTML tag, it was passed as a value into a JavaScript function. In JavaScript, class is a defined keyword for creating classes. So if we use class as an attribute inside the HTML, the same keyword will appear inside the function hence creating a JavaScript error. So instead of class, we use className.

So far we have learned how to use a JavaScript function to create an HTML element. We also learned that it is a complex procedure. But how do we actually plan to tackle it? That's where JSX comes in. JSX is simply assigning an HTML element to a JavaScript variable.

const element = <h1>Hello World</h1>;
Enter fullscreen mode Exit fullscreen mode

Here we have created a JavaScript variable element and assigned its value to be <h1>Hello World</h1>. This is called JSX or JavaScript XML. Now, that wasn't hard.

You can output this using:

ReactDOM.render( element, document.getElementById('root'));
Enter fullscreen mode Exit fullscreen mode

Here element gets added to the HTML DOM by render() method and then the div tag with id="root" will be returned.

I talk about how this works in detail in my first and second post.

Adding JS Expression inside JSX using {}

Let's take the following simple JavaScript expression:

const name = 'Mark Twain`;
Enter fullscreen mode Exit fullscreen mode

You can include it in JSX like this:

const name = `Mark Twain`;
const element = <h1>Hello, {name}</h1>;
Enter fullscreen mode Exit fullscreen mode

Here the first line is a simple JavaScript expression assigning the string Mark Twain to the JavaScript variable name.

The second line is JSX where you're trying to assign an HTML element h1 to the JS variable element. Since the name here is a JS variable, we used {} to write it so the compiler actually recognizes it as actual JS and not as the HTML part of JSX.

If we fail to provide {}, then it will simply return Hello, name.

The best way to understand how this works is to translate the above code into pure JS:

const name = `Mark Twain`;
const element = React.createElement("h1", null, "Hello, ", name);
Enter fullscreen mode Exit fullscreen mode

Here you can see that name became an argument of the React.createElement function. But name here is not surrounded by "" hence returning the actual value of the variable name.

You're free to do this with any JavaScript expressions, including functions, direct expressions like 2+2, access inside a JS object using dot operator, etc.

Here are few examples:

const name= {
  firstName: 'Mark',
  lastName: 'Twain'

/*Here we create a JS Object "name" with property "firstName" and "lastName" having property value "Mark" and "Twain" respectively.*/

function fullName(name) {
  return name.firstName + ' ' + name.lastName;

/*Here we create a function called "fullName" that returns the full name of individual by adding "firstName" and "lastName" strings.*/

const fullname = (
    Hello, {fullName(user)}!

/*Showing that we can insert an entire function into JSX using {}.*/

const firstname = (
    Hello, {name.firstName}!
/*Showing that we can access a property inside an object using the dot operator which is also a JS expression hence works inside {}*/

const two = <p>The sum is {1+1}</p>;

/*Just to show you can enter direct expressions like 1+1 inside the {}*/
Enter fullscreen mode Exit fullscreen mode

You can even add JS expression inside an attribute:

const element = <img src={user.profileUrl}></img>
Enter fullscreen mode Exit fullscreen mode

Here, the profileUrl property of the user object can have the value which is the URL of the profile image.

So always remember, to access JavaScript inside JSX, use {}.

Before I end this article, I would like to briefly mention few more takeaways for JSX basics.

if expressions can accept JSX
const greaterthan = () => {
if(a > b) {
return (<p> a is greater </p>);
return (<p> b is greater </p>);
Enter fullscreen mode Exit fullscreen mode

The same goes for for loops. You're free to use JSX inside it.
The function used here is the arrow function, an ES6 concept.

Values inside JSX tag are called Childrens

For example:

const element = (
    <h1>Hello World!</h1>
    <h2>Hello Internet!</h2>
Enter fullscreen mode Exit fullscreen mode

Here <h1>Hello World!</h1> and <h2>Hello Internet!</h2> are children of div tag.

Keep in mind that you can access children using props.children to be used elsewhere. I will talk about that in more detail in the next post.

Without Children, JSX tag can be self-closing
const element = <img src={user.profileUrl} />
Enter fullscreen mode Exit fullscreen mode

That's it for the basics. Thanks for your time. In the next post, we will talk about a more advanced JSX concept called props.

Update: The next post is here. Or See all posts in the series.

Discussion (0)

Editor guide