DEV Community

Cover image for Let’s Talk About JSX, Baby
Michael Lombard
Michael Lombard

Posted on

Let’s Talk About JSX, Baby

What is JSX? The official name for JSX is JavaScript XML, and it is a syntax that combines JavaScript and HTML used in writing code with React. Although JSX is commonly used in React, JSX and React are two different tools. They are often used together, but can be used separately. JSX is a specific syntax, while React is a JavaScript library.

JSX with React:

Function MyDog = () {
  const name = ‘Dot’;
  const age = 3;

  return (
    <div>
      <h1>Hello, my name is {name}!</h1>
      <p>I am {age} years old.</p>
    </div>
  );
};

ReactDOM.render(<MyDog />, document.getElementById('root'));`
Enter fullscreen mode Exit fullscreen mode

In this example we define a function called MyDog. Within the function we declare two variables name and age. We also give the variables values. The value of name is Dot, and the value of age is 3. The JSX code within the return statement will be the output of our component. The last line in this example is calling
ReactDOM.render(, document.getElementById('root'));,
We are instructing React to render the MyDog component and place it inside the DOM element with the id of 'root'. The component will then be displayed on the web page wherever the element with that id is located.

Let’s look at a JavaScript example:

const myComponent = () => {
  const name = ‘Dot’;
  const age = 3;

  const container = document.createElement('div');

  const heading = document.createElement('h1');
  heading.textContent = `Hello, my name is ${name}!`;

  const paragraph = document.createElement('p');
  paragraph.textContent = `I am ${age} years old.`;

  container.appendChild(heading);
  container.appendChild(paragraph);

  document.getElementById('root').appendChild(container);
};

myComponent();

Enter fullscreen mode Exit fullscreen mode

This example is doing the same thing as JSX, but as you can see it requires a lot more typing. This is one of the main differences between JSX syntax and JavaScript.

JSX is a declarative syntax: Describing the result without instructing how to do it implicitly.
JavaScript is an imperative syntax: Describing how the program should do something explicitly.

The Rules of JSX

  1. Return a single root element
  2. Close all the tags
  3. camelCase all most of the things!

[https://react.dev/learn/writing-markup-with-jsx#the-rules-of-jsx]

Top comments (0)