articles

An Introduction to JSX

JSX is a JavaScript UI engine based on XML that enhances the HTML syntax for creating reusable components. JSX is about writing less for your React components, but getting more out of them. JSX allows a developer to use the declarative power of XML to describe what the user interface looks like, without writing JavaScript code.

 

It also enables developers to define templates for dynamic content, while using JSX safely with React. As developers know, HTML is the basic markup syntax of web pages, traditional JavaScript is no longer limited to the <script> tags. Moreover, it can be reused and shared with CSS.
 
Here we will try to develop a basic understanding of what JSX is and what is its possible scope. 

What is JSX?

 
JSX is a programming language that lets you do powerful things with very little code, but it's not as well known as ES6 or React Native.
 
JSX breaks down human-readable HTML into a single file. It enables you to produce UI components and use them in apps. It's easier to read, write, and maintain than pure JavaScript.
 
JSX is a JavaScript-based XML-like syntax that allows your HTML and components to be mixed together. For example, you could embed an HTML table in a React component to show tabs or results.
 
JSX makes it possible to use no-compile code similar to HTML on the client-side. It can be used with advanced features like XML parsing and virtual DOM.
 
Another use of JSX is defining the appearance of your DOM elements. You can use the same attributes as you would if you were using plain HTML. 

Why Should You Use JSX?

 
JSX may be different from what most people are used to, but it’s going to feel familiar if you’ve ever worked with React or other similar technologies. It will feel just like natural JavaScript.
 
JSX makes coding easier for developers by adding a layer between what you write and how it renders on-page. 
 
This translates into cleaner code that looks pretty much the same as what your page will render at the end. It allows for logical separation of concerns and reuse of components without needing to create templates and duplication of logic in the render.
 

DSL (Domain Specific Language)

 
JSX may look like XML to you, but it’s a Domain Specific Language (DSL) that is compiled into JS code at runtime.
 
This enables powerful developer productivity with a lower learning curve and has simplified the usage of React Native for end users.
 
Here is an example:
 
const element = <h1> Hello, World! </h1>
 
This part “<h1> Hello, World! </h1>;“ is not HTML but JSX which will not render on HTML but React classes.
 
JSX is a transformation that takes HTML code and translates it into React code. This new language provides hooks for external languages at any level in the component hierarchy, keeping the spaghetti out of your code.
 
Use any web technology, such as Markdown or HTML templates and eliminate XPath, XSLT, and CSS preprocessors from your project.
 

How Does JSX Work? 

 
JSX is an easy to use interface that separates your HTML and your code. The JSX code is converted into a JavaScript function during compilation, which is why it’s loaded as a standalone module instead of part of the main codebase. 
 
You can use React.createElement() to create a React component in pure JavaScript. Its straightforward syntax allows you to create a React components independent of the render function.
 
You might want to use React without JSX, but we will advise against that as it may not look pretty. In fact, it may look really bad!
 

Observe:

React with JSX

class S extends Component {
render() {
return (
<div> Hello my name is  <span> { this.props.myName }</span></div>
)
}
} React without JSX class S extends Component {
render() {
return React.createElement (
"div",
null,
" Hello my name is",
React.createElement (
"span",
null,
this.props.myName
)
)
}
}
 
See the point here? JSX saves you from a lot of spaghetti code. 
 

Type scripting

 
Coders love the benefits of TypeScript and its lean typing system. 
 
A benefit of JSX is that it’s possible to take advantage of IntelliSense when coding in a tool like Visual Studio.
 
TypeScript has a compiler and plug-in for use with Visual Studio or any text editor. The default install of the latest version adds roughly 28 MB to your project size, so if you’re working with limited storage capacity or bandwidth, then this is something to keep in mind.
 
But TypeScript is not JavaScript. There’s no way it can support JSX, right? Well, that was indeed the case. Until now!
 
You can now enjoy type checking for JSX in all of your favourite tools as if they were TypeScript: all your tooling can be written in TypeScript while you can write the logic in JSX.
 

Security In JSX 

 
JSX adds additional security protections, addressing known security vulnerabilities. Experience better security, as JSX can prevent errors and speed up your development process. 
 
XSS attacks are the most common security threat on the web as JavaScript code is commonly embedded directly inside HTML without any sanitization. Cross-site scripting vulnerabilities are one of the most common and serious flaws in web applications. In many cases, they can be exploited to completely take over a website.
 
JSX removes the possibility of XSS from JavaScript and HTML code and issues like cross-site scripting is eliminated.
 
JSX won't inject anything that you haven’t written in your code explicitly.
 

Using JSX In React

 
JSX is used for defining HTML markup in React render functions, and it allows code that closely matches the structure of the UI. A requirement of any modern JavaScript-based framework is a solid and powerful templating system -- like JSX.
 
Templating allows you to create a single source for your code--your templates--then easily build them in various contexts. You’ll be able to represent components as HTML instead of writing logic directly in render methods, which will make your code more consistent and readable.
 
Let us see how to incorporate JSX into your React web apps.
 

Transpiling And Creating React App 

 
JSX is like grammar for HTML in JavaScript code; it allows you to express your app's UI and logic with HTML tags and attributes. It works hand in hand with React.
 
Because of its familiarity, writing UIs in JSX feels more natural than writing React components in pure JavaScript arrays and objects. However, JSX needs to be transpiled first before we can use it on the web.
 
The faster way of doing it is by using Babel with the --transform option. Transforming JSX into JavaScript isn't easy, but the latest Babel package makes it all a cinch.
 
You can also use Facebook’s create react tool app. If you want to go this way, you have to install node and npm.
 
Start by creating a React app after installing node.js
 
npx create-react-app myapp
 
Navigate to its folder and then start the server
 
cd myapp

npm start Understanding basic expressions
const element = <h1> Hello, World! </h1>
ReactDOM.render(element, document.getElementById('root'));
 
If you observe the code, you will see that the H1 tag is not using any quotes. That is because it has been used as an expression in language and not a mere string.
 
Similarly, in the following code,
 
function getGreeting(name) {

return `Hello world ${name}`;
} const element = <h1> {getGreeting('Name')} </h1>
ReactDOM.render(element, document.getElementById('root'));
 
You will see that we have used JavaScript in JSX tags by surrounding them with the curly brackets.
 
Furthermore, look at the parent child relationship in the following code:
 
function getGreeting() {

return (
<h2> Welcome </h2>
)
} const element = <div>
<h1> Hello world </h1>
{ getGreeting() }
</div> ReactDOM.render(element, document.getElementById('root'));
 
Similar to the HTML, JSX will also have children. They can be expressions, elements or strings.
 

Working With Conditional Statements 

 
JSX doesn’t have the standard if then else statements rather it returns a particular value as false, true, or undefined to stop the element from rendering itself. Take for example the following code:
 
const logged in = true;

const element = <div>
<h1> Hello! </h1>
<h2>
{ (loggedIn) ? 'Welcome back' }
</h2>
</div>
 
Here is another example
 
ReactDOM.render(element, document.getElementById('root'));

const element = (
<div>
<h1> Hello! </h1>
<h2> Good to see you. </h2>
</div>
);
 

Working With Loops

 

As JSX doesn’t support the IF THEN ELSE statements, it also doesn’t support the FOR statements. What you can do is use the array.map() method.
 
This code will list out the names of some groceries.
 

Observe

 

const items = [

'Butter',
'Sausages',
'Eggs'
]
const element = <div>
list:
<ul>
{items.map(item => <li>{item}</li>)}
</ul>
</div>
ReactDOM.render(element, document.getElementById('root'));
 

Working With Custom Components 

 
Using JSX to work with custom components is significantly less intimidating than it looks. You can define custom components with complex logic, using JSX and stateless functional components.
 
After years of adding HTML markup to JavaScript templates, JSX is now the natural and intuitive way to work with web components.
 
function FunctionComponent() {
    
return <h2>Simple HTML element.</h2>
} class ClassComponent extends React.Component {
render() {
return <h2> Simple HTML class component.</h2>
}
} const element = <div>
<FunctionComponent />
<ClassComponent />
</div>; ReactDOM.render(element, document.getElementById('root'));
 
You can define custom elements as ES6 class or functions. This is a very simple example that will display some basic HTML elements.
 

Forms

 
Forms work differently in JSX. The following form will accept a single name and will exhibit default HTML behaviour. But it is recommended to have a separate JavaScript to get user data since JSX elements keep some internal state. This code will browse to another page after submission. This behaviour works in React but it is recommended to use JavaScript to handle form submissions. 

<form>
    
<label>
Name:
<input type="text" name="name" />
</label>
<input type="submit" value="Submit" />
</form>
 

Event Handling

 
JSX is slightly different from react when it comes to handling events on DOM. In JSX you pass the functions as events handlers rather than plain strings.
 

Observe in HTML

<button onclick="action()">

Activate Lasers
</button>
 

Now in React

<button onClick={action}>  
    
Activate Lasers
</button>
 
The JSX has many built-in event handlers that make it easy to attach event listeners to HTML elements.
 
The onClick attribute automatically creates an event listener for the click event so you don’t have to do anything.
 
For visual confirmation, they use the onMouseOver attribute which also clicks things when you move your cursor over them.

function handleEvent(e) {

alert('Button clicked!');
console.log(e);
} const element = <button onClick={handleEvent}>Test click</button>; ReactDOM.render(element, document.getElementById('root'));

Conclusion

 
JavaScript is a powerful language, but it also tends to be verbose. If you want to quickly build simple user interfaces, JSX offers a shorter and more elegant solution.
 
JSX codes HTML elements in a syntax that appears similar to JavaScript. It helps you build large projects faster, and because JSX sits directly next to regular JavaScript code, it’s easy to get started.
 
By learning JSX you will be able to transition smoothly into building SPA applications using React + Redux.
 
We hope that this brief introduction to JSX will help you in understanding JSX better and how you can implement it in your future apps.
 
Looking to elevate your project? Reach us for expert guidance.
Facebook Linkedin