JSX in ReactJS

JSX in ReactJS

Hello javascript enthusiast, hope you are doing good. I started learning react recently, while learning it I came to know about JSX. So in this blog I will be trying to explain what is JSX and how to use it in react and some other points of using JSX.

JSX stand for Javascript XML it is a javascript extension syntax. It is used to write HTML inside the javascript and add it to DOM without using functions like createElement() and appendChild().
Let's see How it looks like,

const element= <h1>Hello World<h1>

If we look at above code it is neither a string nor a HTML element, This is one of the simple JSX. Here content of element is not any primitive types it contains html code so it is not valid javascript code. So to convert this to browser understandable code we use Babel which is one of the javascript transpiler.
This is mainly used in React to define the UI based on the requirement, like we can define the elements anywhere in the scope and use them whenever required.

How JSX transpiled in Babel?

Whenever we write JSX code it will be in browser non-understandable form, So Babel takes care of converting it to browser undertandable form. Let's see how it is represented before compiling,

export default function App() {
  const jsx=<h1>This is JSX</h1>
  console.log(jsx)
  return (
    <div className="App">
     {
       jsx
     }
    </div>
  );
}

Here in this it will render This is JSX. If we check the console it will show how JSX is stored and after processing JSX it will render on screen.
console will display like,

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

So Babel takes these information and converts it to browser undertandable form and renders on the screen.

How can we write code without JSX?

Let's see one example,

import React from "react"
export default function App() {
  const heading = React.createElement("h1", { id: "jsx" }, "this is JSX");
  const jsx = React.createElement("div", { id: "append" }, heading);
  console.log(jsx)
  return (
    <div className="App">
     {
       jsx
     }
    </div>
  );
}

CodeSandBox
Here in this example nested elements created, If we look at console we can see like,

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

What happens if we use adjacent elements without parent?

Let's understand it by looking at one example,

export default function App() {
  return (
    <h1>Hello</h1>
    <h2>World</h2>
  );
}

If we compile this, we get error as JSX elements must be wrapped in tag. Here it is trying to return 2 elements but it is not possible so required to wrap adjacent elements inside parent tag. Based on the requirement we can use tags like div or it can also be wrapped by using empty tag i.e <> </> but it expects key attribute if not provided then shows warning. Few other ways to solve this problem are using arrays to return and using React.Fragment component to enclose adjacent elements.

How to add comments in JSX

Comments in JSX looks similar to CSS comments,

<h1>Hello javascript</h1>

For the above code comment can be added by enclosing it in JSX expression syntax by using /* */.

{ /* <h1>Hello javascript</h1> */ }

How to use javascript code inside JSX?

For using javascript code inside JSX we need to use curly brackets { } and inside this we can write only expressions which can be evaluated to some value.
For example,

export default function App() {
  const value=10;
  return (
    <div className="App">
     <h1>Value is { value }</h1>
    </div>
  );
}

While using javascript code we need to know which are valid and which are not valid,

Valid type of data for rendering

  1. Simple string
  2. Number
  3. Array
  4. Object property which which can be evaluated to some value
  5. function call that will return some value
  6. map method that which will be returning array
  7. JSX itself can also be used.

Invalid type of data for rendering

  1. Any loops like for, while etc and if statements
  2. Variable declarations
  3. function declarations
  4. Object

You may think that array can be used but why not Object, This is because if we have array like [ 1, 2, 3] this and if we use it in JSX like <p> { [ 1, 2, 3] } </p> then while rendering it will be looks like <p>{1}{2}{3}</p>, but in case of Object it is not clear like how key-value pairs should be seperated like by using , or should it be displayed in JSON format, so When we try to display whole object it gives error.

Now we know that if statement cannot be used inside JSX, but there is one alternative for this i.e conditional operator. Let's see how it can be used,

export default function App() {
  const value=10;
  return (
    <div className="App">
     {
       value ? "Present":"Not Present"
     }
    </div>
  );
}

Similarly we can also use && and || operators.

How to add class or id to elements in JSX

Normally for html element we use class for adding class to element but in JSX we need to use className for adding class to element.
For example,

export default function App() {
  const value=1;
  return (
    <div className="App">
      <h1 id={value}>Hello id</h1>
      <h1 className="check">Hello class</h1>
    </div>
  );
}

Conclusion

In this article we learnt about different What is JSX and how it can be used in different scenarios, some important points are,

  1. Every JSX is converted into React.createElement.
  2. Limitations for using javascript in JSX.
  3. Usage of className instead of class in React.

Thank you for Reading...

References:

  1. freecodecamp.org/news/jsx-in-react-introduc..
  2. reactjs.org/docs/introducing-jsx.html