React

Last Updated: 3/15/2023

JSX

  • JSX stands for JavaScript XML.
  • JSX allows us to write HTML directly within the JavaScript code.
  • You are not required to use JSX, but JSX makes it easier to write React applications.

With JSX

const hello = <h1>Hello World</h1>;
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(hello);

Expressions in JSX

  • You can write expressions inside curly braces { }.
  • The expression can be a React variable, or property, or any other valid JavaScript expression. JSX will execute the expression and return the result:
const element = <h1>You can include javascript expression {5 + 5}</h1>;

Large Block of HTML

  • If your markup is multiple lines, you must wrap it in a pair of parentheses like this:
const element = (
  <ul>
    <li>Apples</li>
    <li>Bananas</li>
    <li>Cherries</li>
  </ul>
);

One Top Level Element

  • HTML code must be wrapped in ONE top level element.
  • You must put them inside a parent element, like a div element.
  • You can use a fragment to wrap multiple lines. This will prevent unnecessarily adding extra nodes to the DOM.

Using Fragment

const myElement = (
  <>
    <p>I am a paragraph.</p>
    <p>I am a paragraph too.</p>
  </>
);

Using Parent Element

const myElement = (
  <div>
    <p>I am a paragraph.</p>
    <p>I am a paragraph too.</p>
  </div>
);

Elements Must be Closed

  • JSX follows XML rules, and therefore HTML elements must be properly closed.
  • JSX will throw an error if the HTML is not properly closed.
const myElement = <input type="text" />;

Adding CSS Class

  • JSX is rendered as JavaScript, and the class keyword is a reserved word in JavaScript, you are not allowed to use it in JSX.
  • Use attribute className instead.
const myElement = <h1 className="myclass">Hello World</h1>;