An Intro to JSX
Bipin Rajbhar
Posted on October 27, 2020
What is JSX?
In simple words, JSX is just syntactic sugar on the top of raw React APIs.
// JSX (HTML-like Syntax)
const reactElement = <h1>Hello World</h1>;
// compiles to raw React APIs
const reactElement = React.createElement('h1', {}, 'Hello World');
JSX is not actually JavaScript, so we need a compiler to compile our JSX. Babel is one such tool we gonna use to compile our JSX.
Babel is written in JavaScript we can actually run it directly in the browser to compile our code on the fly.
To use babel in our Web Application. We need to include a script tag for babel and then we need to change the type of the script from text/javascript
to text/babel
. So that babel can identify which script tag needs to be compiled.
<script src="https://unpkg.com/@babel/standalone@7.9.3/babel.js"></script>
<script type="text/babel">
// JavaScript + React
</script>
Let's try to recreate Example 1 from the previous article using JSX.
Sample Code
<body>
<div id="root"></div>
<script src="https://unpkg.com/react@16.7.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.9.3/babel.js"></script>
<script type="text/babel">
// JSX
const divElement = <div>Hello World</div>
ReactDOM.render(divElement, document.getElementById('root'))
</script>
</body>
The compiled code is added to the
head
tag.
Example 1
Interpolation
Interpolation is defined as "the insertion of something of a different nature into something else".
Sample Code
<body>
<div id="root"></div>
<script src="https://unpkg.com/react@16.7.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.9.3/babel.js"></script>
<script type="text/babel">
// interpolation
const divElement = <div>{new Date().toLocaleString()}</div>
ReactDOM.render(divElement, document.getElementById('root'))
</script>
</body>
Example 2
I hope you learned something from this article and if you have any doubt please leave a comment. I will be very happy to answer all your questions.
My name is Bipin Rajbhar and I am a software engineer at QuikieApps and you can follow or connect to me on Twitter and Linked In
Resources
The Beginner's Guide to React
Epic React
Posted on October 27, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.