jsx in react
JavaScript / React JS

What is JSX in React JS?

jsx in react

Are you looking for an article where you can understand what is JSX in React? If so, this article is for you. Here, I’m going to explain it in-depth and try to make you understand how you can use JSX in React to save your time and work like a pro.

With the increasing popularity of ReactJS, there’s a need to know such things as ECMAScript and JSX. Several people have asked about them, and if you’re among them, you’ve landed on the right page.

In this discussion, we’ll talk more about JSX, what it stands for, how it works, why you can use it, and many more. Let’s begin by looking deeper into the term itself.

What is JSX?

JSX stands for JavaScript XML and is an XML-like syntax used by React that extends ECMAScript such that XML-like text can co-exist with JavaScript Code. Basically, it’s a syntax extension of regular JavaScript used to create React elements. It allows us to write and add HTML in React.

You can utilize React without JSX, though JSX makes React a bit more stylish. Like XML, the JSX tags have a name, attributes, and children. An attribute enclosed in quotes is called a string, while that wrapped in braces is JavaScript expression.

How does JSX work in React?

Here is a simple example of what happens when you write code with and without JSX in React JS. Try the given examples yourself so that you can get a better understanding of it.

With JSX:

class HelloMessage extends React.Component {
  render() {
    return (
      <div>
        Hello {this.props.name}
      </div>
    );
  }
}
ReactDOM.render(
  <HelloMessage name="Dheeraj" />,
  document.getElementById('hello-example')
);

Without JSX:

class HelloMessage extends React.Component {
  render() {
    return React.createElement(
      "div",
      null,
      "Hello ",
      this.props.name
    );
  }
}

ReactDOM.render(React.createElement(HelloMessage, { name: "Taylor" }), document.getElementById('hello-example'));

How to use JSX in React?

JSX looks similar to a regular HTML in most cases, but there are some things to consider when working with it. These include:

  • Nested elements. JSX enables you to add elements as children of other components. For example, imagine that you want to deliver several tags a time; you first need to nest all of them under a parent tag rendered to the HTML. All other subtags will be child tags/ children to the parent element. All the elements must be closed properly to avoid an error.
  • JavaScript expression. You can use regular JavaScript expressions with JSX. Embedding any of these expressions in a piece of code written with JSX requires that it’s wrapped in curly braces {}. JSX doesn’t allow the use of “if-else,” but we can use conditional expressions.
  • Attributes. You can use attributes with HTML components for JSX, just like it is done with standard HTML. But, JSX uses camelCase naming convention instead of the standard HTML naming convention. For instance, class becomes className and for becomes htmlFor . This happens to avoid issues that result from the HTML naming, where names like class tend to be reserved keywords in JavaScript. JSX also enables us to specify attribute values as string laterals (hard-coded strings using quotes) or as expressions (using curly braces). You can also use custom attributes whose names will be prefixed by “data-”.
  • Comments. Like we use JavaScript expression with JSX, we can do so with comments. These start with /* and ends with */, though enclosed in curly braces.
  • Styling. React prefers the use of inline styles. When setting these styles, the camelCase syntax should be used, and React will automatically attach px after the figure value on specific elements.

Creating React Elements with JSX

So, how can you describe elements with JSX? JSX is the coded language of React elements, and the foundation of any markup that React will render into an app. Since it allows you to write JavaScript in markup, you can make good use of JavaScript functions and methods, including short-circuit conditionals’ evaluation and array mapping. Below steps can help in creating React elements with JSX:

1. Add markup to a React Element

This step involves adding basic HTML-like syntax to an existing React element. You’ll add standard HTML elements into a JavaScript function and view the compiled code in a browser. Grouping the elements will also help React to assemble them with minimum markup resulting in a clean HTML output.

2. Add Styling to an Element with Attributes using JSX

You’ll now style your component elements to understand how HTML attributes work with JSX. Several styling options in React are available, including those that use preprocessors and others that involve writing CSS in JavaScript. This is where you’ll also add classes, ids, and aria tags, and work with data as variables and strings.

3. Affix Events to the Elements

React uses attributes to describe how your elements should respond to user events. Thus, you’ll affix events to elements using special attributes and capture a click event on a button element. You can add several event handlers accessible through to HTML elements.

4. Mapping over Data to Create Elements

This step involves more than using JSX as a simple markup; instead, it combines it with JavaScript to generate dynamic markup that minimizes code and enhances readability. JSX doesn’t restrict you to XML/HTML-like syntax; it also allows you to use JavaScript directly in your markup. To create React components, you should convert the data to JSX elements by mapping over the data.

5. Show Elements with Short-Circuit Conditionals

At this point, you’ll show specific HTML elements conditionally by using short-circuiting. This enables you to generate components that can show or hide HTML depending on extra information that gives your components flexibility to handle numerous situations.

For instance, sometimes, you would want to show the user only an alert message or display some private account details for an admin that shouldn’t be seen by a normal user. Using short-circuiting will help you in that case.

I would like to give you one more example of this technique. So that you can get a better understanding of how does it work with React JS.

Suppose we have to create a div with the name sidebar. So with JSX, we can write like the given example. It is very simple and easy to do this.

<div className="sidebar"/>

The above code will be compiled into this.

React.createElement(
  'div',
  {className: 'sidebar'}
)

Using JSX you write less code and get the same results to increase productivity while working with React JS.

Why use JSX in React?

You can use React without JSX, but the benefits of using it so far surpass our imagination. With JSX, lots of things are more straightforward, and these might include:

  • Using formatting libraries. Things like Ember and Backbone make number formatting on the web simple, but since JSX is closely tied to HTML, it’s more efficient and straightforward to format libraries.
  • Rendering lists of data. As seen above, using JSX with React is perfect when you render lists of data. With it, it’s as simple as transforming an array of data into an array of related markup.
  • Keeping markup clean and organized. JSX enforces better code standards for markup. It gives an excellent, clean way to display React elements in code such that they are sensible and readable.

The other pros of JSX are:

  • It is quicker than regular JavaScript as it executes optimizations while translating to the standard JavaScript.
  • It simplifies the creation of templates for us, with the only drawback being the inability to read it by a browser.

Conclusion

Indeed, JSX is an appropriate way to work with React and ensure you obtain a clean and readable app. It involves several features that make its functionality one of a kind. By using JSX, you can construct dynamic and flexible components faster to develop your application.

Author

I am a Full Stack Web Developer. I have more than 8 years of experience in the web design and development industry.

Leave a Reply

Your email address will not be published. Required fields are marked *