DEV Community

Fatima Alam
Fatima Alam

Posted on

JSX in React

What is JSX?
JSX is a JavaScript Extension Syntax used in React to easily write HTML and JavaScript together.

const jsx = <h1>This is JSX</h1>
Enter fullscreen mode Exit fullscreen mode

This is simple JSX code in React. But the browser does not understand this JSX because it's not valid JavaScript code.
So to convert it to browser understandable JavaScript code, we use a tool like Babel which is a JavaScript compiler/transpiler.
or you can use create-react-app which internally uses Babel for the JSX to JavaScript conversion.

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

const App = () => {
 const number = 10;
 return (
  <div>
   <p>Number: {number}</p>
  </div>
 );
};
Enter fullscreen mode Exit fullscreen mode

Inside the curly brackets we can only write an expression that evaluates to some value.

Following are the valid things you can have in a JSX Expression:

  1. A string like "hello"
  2. A number like 10
  3. An array like [1, 2, 4, 5]
  4. An object property that will evaluate to some value
  5. A function call that returns some value which may be JSX
  6. A map method that always returns a new array
  7. JSX itself
  8. Following are the invalid things and cannot be used in a JSX Expression:

  9. A for loop or while loop or any other loop

  10. A variable declaration

  11. A function declaration

  12. An if condition

  13. An object

In the case of an object, it’s not clear how the object should be displayed. For example, should it be comma-separated key-value pairs or should it 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 object properties instead.

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

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

const App = () => {
  const isAdmin = true;
  return (
    <div>
      <p>isAdmin is {`${isAdmin}`} </p>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)