How to render Jsx code in the browser

About

Jsx is the react language that permits to write react element in a markup way (and not in pure javascript).

Therefore to be able to show the result of Jsx, it needs to be transpilled (ie converted to pure javascript).

Normally, you will work in Node with a framework that will do the babel transpilling for you in the background.

For a demo purpose and to understand how it works, this is how you set up a browser to render JSX

Steps

Adding the React and babel libraries

Library: Next to the React and ReactDom library, you need to add the Babel library.

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.js"></script>
<script type="text/javascript" src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

Tagging the script as babel mime

Inside your HTML page, The Jsx script that Babel will transpile must be tagged with the type text/babel

<script type="text/babel">
    function formatName(user) {
      return user.firstName + ' ' + user.lastName;
    }

    const user = {
      firstName: 'Foo',
      lastName: 'Bar'
    };

    //  wrapping it in parentheses to avoid the pitfalls of automatic semicolon insertion.
    const element = (
      <h1>
        Hello, {formatName(user)}!
      </h1>
   );
</script>

Adding the HTML root element

The Root element where the React component will render

It's called the “root” DOM node because it's the root of the React DOM Tree and React will render all its element inside it.

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

Render

The rendering function that takes the React DOM tree and render it inside the root Html element

<script type="text/babel">
    ReactDOM.render(
      element,
      document.getElementById('root')
    );
</script>

Result





Discover More
React - JSX

JSX is a Javascript HTML Like language that compiles to Javascript React API. The first motivation of JSX is that reading and writing React elements, are easier. It permits to: write JSX elements...



Share this page:
Follow us:
Task Runner