What is JSX and how to use it within React

JSX with React

For React developers, JSX is a very familiar term. But even if you haven't worked with React you probably have heard of JSX. And if you are completely unaware of this, get ready to have some cringe.

While working on a basic HTML project you usually write markup in .html file, and javascript in .js file or in a script tag to embed that in the .html file. Right?

With the help of JSX, we will reverse the rule of writing js code in HTML. We will write HTML in js files. The React developers shake the JS community introducing this very powerful concept of writing HTML within the js file.

I hope this article would be very interesting.

JSX(JavaScript XML) allows us to write HTML within JavaScript(React), and place them in the DOM with the help of the Babel library. This doesn't require to use methods like createElement() or appendChild().

While JSX is not HTML, it is compiled to HTML behind the scenes with Babel. Essentially, Babel takes the latest version of JavaScript (ES6 or newer) and produces an equivalent code that is compatible to run in your web browser. So, yes, you’ve guessed it, ReactJS can be used without JSX, but it is highly recommended to use.

"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." — reactjs.org

It's time to get our hands darty. Take a look at the 2 examples below:

First one

const myelement = <h1>Let's React with JSX</h1>;

ReactDOM.render(myelement, document.getElementById('root'));

Second one

const myelement = React.createElement('h1', {}, 'Reacting without JSX!');

ReactDOM.render(myelement, document.getElementById('root'));

From this very simple example, you can see how JSX makes our life easier. JSX is an extension of the JavaScript language based on ES6, and is translated into regular JavaScript at runtime.

Writing Expressions in JSX

JSX allows adding expressions to HTML inside curly braces {}. In the following example, we have declared a variable name and then used it inside JSX.

const name = 'John Patel';
const element = <h1>Hello, {name}</h1>;

ReactDOM.render(
  element,
  document.getElementById('root')
);

And, expression means any expression. You can also do math which was previously a nightmare within HTML markup.

const myAge = <h1>I have {3+5} books</h1>;
ReactDOM.render(
  myAge,
  document.getElementById('root')
);

Adding block of HTML

To write HTML on multiple lines, just put the HTML within parentheses like below. Then use it where you want to render.

const friendList = (
    <ul>
        <li>George</li>
        <li>Safa</li>
        <li>Shouvik</li>
        <li>Samio</li>
    </ul>
)
ReactDOM.render(
  friendList,
  document.getElementById('root')
);

Want some fun? Let's rewrite the above code block with another js function map().

const myFriends = ['George', 'Safa', 'Shouvik', 'Samio'];
const friendList = (
    <ul>
        {myFriends.map(friend => <li>{friend}</li>)}
    </ul>
)
ReactDOM.render(
  friendList,
  document.getElementById('root')
);

Now that we have some basic idea about JSX. Let's see another example. We have information about a person in a javascript object format. Our task is to use all the information in an HTML block to visualize profile.

const developerOne = {
    name: "John Patel",
    title: "Sr. Web Developer",
    image: "https://example.com/bucket/img/developer-one.png"
}
const profileOne = (
    <div>
        <img src={developerOne.img} alt={developerOne.name} />
        <h2>Name: {developerOne.name} </h2>
        <p>Title: {developerOne.title} </p>
    </div>
)
ReactDOM.render(
  profileOne,
  document.getElementById('root')
);

If we want to visualize all the employees' profile, that's easy right? We just need to map through the array of employees' data.

import React from "react";

const App =()=> {
  const developers = [
    {
      name: "John Patel",
      title: "Sr. Web Developer",
      image: "https://example.com/bucket/img/developer-1.png"
    },
    {
      name: "John Safa",
      title: "Sr. Web Developer",
      image: "https://example.com/bucket/img/developer-2.png"
    },
    {
      name: "John Samio",
      title: "Sr. Web Developer",
      image: "https://example.com/bucket/img/developer-3.png"
    }
  ];

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <div>
        {developers.map(profile => (
          <div>
            <img src={profile.img} alt={profile.name} />
            <h2>Name: {profile.name} </h2>
            <p>Title: {profile.title} </p>
          </div>
        ))}
      </div>
    </div>
  );
}
export default App;

Finally

JSX was introduced to simplify markup in React applications. It's nothing difficult to learn. Proper understanding of JSX increases productivity of developing a React application.