If youā€™re new to React, youā€™ll likely have heard about JSX, or JavaScript XML ā€” itā€™s an XML-like code for elements and components. In this article, weā€™re going to take a look at what JSX is & why we should use it in our React applications. Weā€™ll also take a look at what elements are, and how we can render them to the DOM.

What is JSX?

As mentioned, JSX is an XML-like code which we can use when coding with React. It was developed by the team at Facebook & is meanā€™t to provide a more concise syntax, helping to simplify the developer experience. Letā€™s take a look at our first example:

const greeting = <h1>Hello, World!</h1>;

Simple, right?

What we have here is neither a string nor HTML. Itā€™s JSX! We can use it to harness the full power of JavaScript when building our UI elements. And while itā€™s not mandatory, itā€™s certainly an extremely useful tool ā€” it does a great job of making it clear when weā€™re working with UI inside of our JavaScript code.

Using JSX

Letā€™s extend our above example to include an embedded expression.

const user = 'Bob Burger';
const greeting = <h1>Hello, {user}</h1>;

ReactDOM.render(
  greeting,
  document.getElementById('root')
);

We use curly braces {} to embed the variable into our JSX expression. And within those curly braces we could embed any valid JavaScript expression. Such as user.firstName or printName(user) for example.

Note: Weā€™ll look at rendering in detail later in the article, donā€™t be to concerned about the above render method just yet!

Letā€™s embed the result of a called JavaScript function:

function printName(user) {
  return user.firstName + ' ' + user.lastName;
}

const user = {
  firstName: 'Bob',
  lastName: 'Burger'
};

const greeting = (
  <h1>
    Hello, {printName(user)}!
  </h1>
);

ReactDOM.render(
  greeting,
  document.getElementById('root')
);

JSX Under the hood

So whats actually going on with JSX, when we render components?

function Greeting() {
  return <h1>Hello, World!</h1>
}

Each element being rendered by the Greeting component are transpiled down into React.createElement calls. The above example transpiles to:

function Greeting() {
  return React.createElement("h1", {}, "Hello, World!")
}

React.createElement()

Letā€™s see another example:

const greeting = (
  <h1 className="speak">
    Hello, world!
  </h1>
);

When compiled, this code looks as follows:

const greeting = React.createElement(
  'h1',
  {className: 'speak'},
  'Hello, world!'
);

Both of these code blocks are identical. And essentially an object is created like so:

const greeting= {
  type: 'h1',
  props: {
    className: 'speak',
    children: 'Hello, world!'
  }
};

This object is known as a React element, and it functions a lot like a description of what you see on the screen. React uses these objects to build the DOM and keep it up to date.

Essentially, JSX is really just making the React.createElement(component, props, ā€¦children) function much more pleasing on the eye. Another example:

<Navbar backgroundColor = "purple" opacity = {0.8}>
  Menu bar
</Navbar>

Will transpile to:

React.createElement(Navbar, {
  backgroundColor: "purple",
  opacity: 0.8
}, "Menu bar");

Letā€™s now move on the see a few more conceptsā€¦

Props in JSX

Weā€™ll take a deep dive into props in my next article! For now its good to remember that when building components ā€” theyā€™ll often render children, which require data to render correctly. The parameters we pass in are what we call props. In JSX, there are a few ways we can do this, such as:

// Defaults to "true" if no value is passed
<MyComponent connected />
// String literals passed as props
<MyComponent user= "Bob Burger" />
// Expressions (below example will evaluate to 10)
<MyComponent total = {1 + 2 + 3 + 4} />
// Spread attributes: passes the whole props object
<MyComponent selected = {...this.state} />

Note: if statements and for loops are not expressions in JavaScript, so they cannot be used in JSX directly! Instead, you could code it like so:

function NumberType(props) {
  let answer;
  if (props.number % 2 == 0) {
    answer = <strong>even</strong>;
  } else {
    answer = <i>odd</i>;
  }
  return <div>{props.number} is an {answer} number</div>;
}

We can see our props passed into the conditional, evaluated and then returned ā€” all via JSX.

Children in JSX

As your apps become larger, youā€™ll find some components will need to render children. And then those child components will also need to render further children, and so on! With JSX, we can manage these tree-like structures of elements quite well. The rule of thumb is ā€” whatever elements a component returns become its children.

Lets take a quick look at the ways to render child elements with JSX:

String Literals

<MyComponent>I'm a child!</MyComponent>

In this very basic example, the string Iā€™m a child is a child of MyComponent. And its accessible via props.children of MyComponent.

JSX Elements as Children

Say we want to return an HTML child <header>, which has two of its own children: <Nav /> and <SearchBox />. We could do this like so:

function Header(props) {
  return (
    <header>
      <Nav />
      <SearchBox />
    </header>
  )
}

Expressions

We can also pass expressions as children, to render to our UI. This would be very useful with a to-do list app, for example:

function TodoItem(props) {
  return <li>{props.content}</li>;
}

function TodoList() {
  const todos = ['paint house', 'buy more chips', 'conquer world'];
  return (
    <ul>
      {todos.map((content) => <TodoItem key={content} content={content} />)}
    </ul>
  );
}

Functions

Functions can be useful when handling repetition, such as rendering repeated UI elements. We can create the structures that React will automatically render for us.

Letā€™s look at an example where we use a .map() function to create new pages on a website:

// Array of current pages
const pages = [
  {
    id: 1,
    text: "Home",
    link: "/"
  },
  {
    id: 2,
    text: "About",
    link: "/about"
  },
  {
    id: 3,
    text: "Contact",
    link: "/contact"
  }
];
// Renders a <ul> which generates the <li> children
function Nav() {
  return (
    <ul>
      {pages.map(page => {
        return (
          <li key={page.id}>
            <a href={page.link}>{page.text}</a>
          </li>
        );
      })}
    </ul>
  );
}

To add a new page to our website, we just need to add a new object to the pages array & let React handle the rest!

Rendering Elements

As Iā€™m sure youā€™ve seen throughout this article, when working with JSX weā€™re working with elements to render into our page. An element describes what you see on the screen:

const element = <h1>Hello!</h1>;

Multiple elements such as this when combined, will form components. Weā€™ll be taking a detailed look at components in my next article!

Rendering our elements to the DOM

Typically, weā€™ll have a <div> like so, in our HTML:

<div id="root"></div> 

This is known as our DOM node. Everything inside of it is handled by React DOM.

And to render a React element into our root node, we pass both to ReactDOM.render(), like so:

const element = <h1>Hello!</h1>;
ReactDOM.render(element, document.getElementById('root'));

Hello! will render to our page.

Updating rendered elements

Note that React elements are immutable! Once an element is created, you canā€™t change its children or its attributes. If if wish to update the UI, youā€™ll need to create a new element and pass it to ReactDOM.render().

Wrapping up

And there we go! Weā€™ve covered the basics of JSX and rendering. And I hope youā€™re beginning to see how useful these concepts are to us as developers, building React apps.

By harnessing the power of JSX to pass around elements in JavaScript, weā€™re building very workable code. The structure of JSX plays incredibly well with React, and despite the fact that JSX isnā€™t mandatory ā€” it makes for a fantastic development experience.

Related Posts:


Tim profile image

A little about me..

Hey, Iā€™m Tim! šŸ‘‹

Iā€™m a freelance business owner, web developer & author. I teach both new and experienced freelancers how to build a sustainable and successful freelancing business. Check out myĀ Complete Guide to Freelancing if you'd like to find out more.

While you're here, you can browse through my blogs where I post freelancing tips, code tutorials, design inspiration, useful tools & resources, and much more! You can also join the newsletter, or find me on X.

Thanks for reading! šŸŽ‰