Written by - Saksham Jain

React JSX


JSX stands for JavaScript XML. JSX allows us to write HTML in React with some changes. We can write HTML in React natively but JSX makes it easier to write HTML. JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement() and/or appendChild() methods.

With JSX

const myelement = <h1>I Love JSX!</h1>;
 
ReactDOM.render(myelement, document.getElementById('root'));

Without JSX

const myelement = React.createElement('h1', {}, 'I do not use JSX!');
 
ReactDOM.render(myelement, document.getElementById('root'));

Concepts Of JSX

  1. We can use expressions in JSX using curly braces “” ,JSX will execute the expression. Example:
    const myelement = <h1>React is {5 + 5} times better with JSX</h1>;
    Output :React is 10 times better with JSX
  2. We can also insert large block of element like this
    const myelement = (
        <ul>
          <li>Apples</li>
          <li>Bananas</li>
          <li>Cherries</li>
        </ul>
      );
  3. We can insert multiple elements in react element but there must be a single element on top, we can do this by putting them in a single div container or inside a fragment (...). Example:
    const myelement = (
        <div>
          <p>I am a paragraph.</p>
          <p>I am a paragraph too.</p>
        </div>
      );
  4. Every element must be closed. So, we have to close every empty element with "/>". Example
    const myelement = <input type="text" />;
  5. There are some differences in HTML and JSX HTML like we have to use className instead of class and we have to use all tags in the small cases etc.
    const myelement = <h1 className="myclass">Hello World</h1>;
  6. We can do many things inside curly braces “” like putting a variable,putting a conditional statement or ternary expression and many more.
    const x = 5;
    let text = "Goodbye";
    if (x < 10) {
      text = "Hello";
    }
     
    const myelement = <h1>{text}</h1>;