Click to share! ⬇️

Embedding Expressions In JSX

JSX is an extension to the JavaScript language, and therefore it can accept any valid JavaScript expressions placed inside the curly braces. For example, 4 + 4, user.firstName, or formatName(user) are all valid JavaScript expressions. This allows you to make your JSX more dynamic. In this tutorial we’ll take a look at some additional examples of embedding expressions in JSX markup, as well as some of the rules associated with rendering more than one html tag in a JSX expression. We’ll see that one parent element is needed, and learn of a couple of ways to make sure we meet that requirement.


Starting With A Fresh App

Thanks to the Create React App, it’s super easy to whip up a fresh new application and that is exactly what we’ll do now. We’ll name it cartable, as we want to approximate how a shopping cart works in React.

react $create-react-app cartable
Creating a new React app in C:nodereactcartable.

Install Bootstrap With React

Now, we’re going to add Bootstrap to make the user interface look nicer. So first off, at the terminal we’ll simply install the latest version of Bootstrap like so.

cartable $npm install bootstrap

+ bootstrap@4.3.1
added 1 package from 2 contributors and audited 36233 packages in 35.67s

In order to make use of Bootstrap, we’ll now need to import it in the index.js file like we see here.
index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import 'bootstrap/dist/css/bootstrap.css';

ReactDOM.render(<App />, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

Creating A Components Folder

We’re going to be adding more than one component in this project, so it makes sense to create a folder to hold the components we’ll need. Here, we can create a new folder in the src folder named components.
react components folder

In that components folder, let’s add a new file that will represent an item in the shopping cart. This is the item.jsx file.
item.jsx
item-jsx in components folder

Now just add some simple JSX markup to that file. It is a single h1 tag with the text Cartable!

import React, { Component } from "react";

class Item extends Component {
  render() {
    return <h1>Cartable!</h1>;
  }
}

export default Item;

Let’s add that component to the index.js file so that it can render on the page. Notice that we are removing the default <App /> rendering and replacing it with <Item />.
index.js

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import "bootstrap/dist/css/bootstrap.css";
import Item from "./components/item";

ReactDOM.render(<Item />, document.getElementById("root"));

serviceWorker.unregister();

In the index.html file, we can add a class to the body element since we have installed Bootstrap. This will space things out nicely on the page.

Containers are the most basic layout element in Bootstrap and are required when using our default grid system. Choose from a responsive, fixed-width container (meaning its max-width changes at each break point) or fluid-width (meaning it’s 100% wide all the time).

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <meta name="theme-color" content="#000000" />

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

    <title>React App</title>
  </head>
  <body class="container">
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

There we go, we’re on our way!
react element rendered on the page


Expressions In JSX

You can have more than one tag as part of a JSX expression. So far, we’ve only seen an h1 tag, but what if we want to have both an h1 and a button in the same JSX expression. In order for this to work properly, we need an outer wrapping div. JSX Expressions must have one parent element. In addition, it is best practice to wrap the entire JSX expression in parenthesis ( );.
item.jsx

import React, { Component } from "react";

class Item extends Component {
  render() {
    return (
      <div>
        <h1>Cartable!</h1>
        <button>Increment</button>
      </div>
    );
  }
}

export default Item;

embedded react expression


React.Fragment

You might not want to pollute your HTML markup with excessive div elements. In the example above, we needed to wrap both the h1 and button tags with one single parent element. This is a rule of JSX. The downside, however, is that you will notice if we inspect the markup on the page that there is an extra div element now.
extra div in react markup

We can fix this extra div issue by using the <React.Fragment> tag in place of the <div> element.

import React, { Component } from "react";

class Item extends Component {
  render() {
    return (
      <React.Fragment>
        <h1>Cartable!</h1>
        <button>Increment</button>
      </React.Fragment>
    );
  }
}

export default Item;

react fragment removes extra divs


Adding State To The Component

Now instead of having static content in the JSX expression, we can use some data from the state object to display a value. In this snippet below, we add that state object with a property of count. It’s value is 0. To reference that count in the JSX markup, we use this.state.count.

import React, { Component } from "react";

class Item extends Component {
  state = {
    count: 0
  };
  
  render() {
    return (
      <React.Fragment>
        <span>{this.state.count}</span>
        <button>Increment</button>
      </React.Fragment>
    );
  }
}

export default Item;

The output is displaying the value we had set to the count property.
ui updates from state

If we change the value of the count property, then the UI updates automatically.

import React, { Component } from "react";

class Item extends Component {
  state = {
    count: 400
  };

  render() {
    return (
      <React.Fragment>
        <span>{this.state.count}</span>
        <button>Increment</button>
      </React.Fragment>
    );
  }
}

export default Item;

react state object update


Embedding A Function

It is also possible to embed a function inside of the JSX markup that returns a value. In our Item component below, we have added a styleCount() function. The job of this function is to look at the count state and if it is 0, then return the string value of “No Items”. If the value is greater than 0, then it simply returns that value. In the JSX markup, we can make use of this function with the syntax {this.styleCount()} which outputs whatever value this function returns.

import React, { Component } from "react";

class Item extends Component {
  state = {
    count: 0
  };

  render() {
    return (
      <React.Fragment>
        <span>{this.styleCount()}</span>
        <button>Increment</button>
      </React.Fragment>
    );
  }

  styleCount() {
    const { count } = this.state;
    return count === 0 ? "No Items" : count;
  }
}

export default Item;

There we go! With the count at 0, we see “No Items”.
embedded expressions in react

When the value is above 0, we see that result instead.

  state = {
    count: 500
  };

react embedded function result


Learn More


Embedding Expressions In JSX Summary

Working with JSX takes a little time to get used to, but as you play around with the syntax it quickly becomes familiar. In addition, using a code formatter like the Prettier extension will automatically format and clean up your JSX so that makes it easy to produce good-looking markup with minimal effort.

Click to share! ⬇️