Learnitweb

1. Introduction

In this tutorial, we’ll discuss one of the most important building block of React, the JSX.

While working with React, you may come across like the following:

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

This neither looks like a string nor HTML. JSX (JavaScript Syntax Extension) is a React extension to the JavaScript language syntax.

2. Why JSX?

React components are usually written using JSX, but it is not mandatory. React components can be written purely in JavaScript. But, using JSX for writing components is helpful as it looks like integrating UI and JavaScript code.

3. JSX Compilation

JSX is not directly used and rendered in your browser as it is. Babel compiles JSX down to React.createElement() calls. You can check this yourself using the following link:

https://babeljs.io/repl

For example, try the following:

<h1>Hello World!</h1>

The above element will be converted to the following:

React.createElement("h1", null, "Hello World!");

The objects created like this are called React elements.

After compilation, JSX expressions become regular JavaScript function calls and evaluate to JavaScript objects. This means JSX expressions can be used inside of if statements and for loops, can be assigned to variables, can be accepted as arguments, and can be returned from functions.

Note: Writing something like <h1>Hello World!</h1> doesn’t make anything show up in the browser automatically. This only creates an instruction for React to make it an element. We have to return it from a component for React to use it.

4. Embedding expressions in JSX

Curly braces are used to embed JavaScript expression inside the JSX. For example, in the following code, we are declaring a variable message and using it inside the JSX.

const message = 'Hello world!';
const element = <h1>Message: {message}</h1>;

You can put any valid JavaScript expression inside the curly braces in JSX.

In the following example, we have embedded the result of calling a JavaScript function.

function getTotal(num1, num2) {
  return num1 + num2;
}

function App() {
  return <h1>Total: {getTotal(1, 2)}</h1>;
}

However, this does not work with all types of data. For example, boolean, arrays and objects are not rendered in the same way the string is rendered.

function App() {
  const message = [1, 2, 3];
  return <h1>Message: {message}</h1>;  //prints blank
}
function App() {
  const message = [1, 2, 3];
  return <h1>Message: {message}</h1>;  //prints 123
}
function App() {
  const message = {
    message: "hello world!",
  };
  return <h1>Message: {message}</h1>; //Objects are not valid as a React child
}

4.1 Important note

Trying to display an object doesn’t work but you can provide as object as a ‘prop’. We’ll read about prop in detail later. For now, prop is the short form of properties.

function App() {
	const config= { color: 'blue' };
	<input myProp={config} />
}

5. Attributes with JSX

Double quotes can be used to specify string literals as attributes:

const element = <a href="https://learnitweb.com"> link </a>;

Curly braces can also be used to embed a JavaScript expression in an attribute:

const element = <img src={your_image_url}></img>;

Note: Don’t put double quotes around curly braces when you use curly braces to embed a JavaScript expression in an attribute. You should either use quotes or curly braces , but not both in the same attribute.

6. Multi-line JSX

You can use parenthesis for multi-line JSX. For example:

const element = (
  <h1>
    Hello, world!
  </h1>
); 

7. JSX Prevents Injection Attacks

By default, React DOM escapes any values embedded in JSX before rendering. Everything is converted to a string before being rendered. This helps prevent XSS (cross-site-scripting) attacks.

const title = malaciousInput;
// Following is completely safe as it is escaped and converted to string
const element = <h1>{title}</h1>;

8. Converting HTML to JSX

HTML can not be as it is converted to JSX. Attributes of a HTML element which are name-value pairs are slightly different in the corresponding JSX. Following are the rules of converting HTML to JSX:

Rule 1: All prop names follow camel case.

HTMLEquivalent JSX
<input maxlength=”5″ /><input maxLength={5} />

Rule 2: In JSX, the attributes which are supposed to have numbers as values should be provided with curly braces.

<input maxlength={5} />

Rule 3: In JSX, boolean value ‘false’ should be provided with curly braces. However, in case of the boolean value ‘true’, you need not to specifically write the value.

HTMLEquivalent JSX
<input spellcheck=”true” /><input spellCheck />
<input spellcheck=”false” /><input spellCheck={false} />

Rule 4: In JSX, the ‘class’ attribute is written as ‘className’.

HTMLEquivalent JSX
<div class=”alert” /><div className=”alert” />

Rule 5: In JSX, in-line styles are provided as objects.

HTMLEquivalent JSX
<a style=”text-decoration:’none’; padding-top: ‘2px’;” /><a style={{textDecoration: ‘none’, paddingTop: ‘2px’}} />

Notice the camel-case of textDecoration and paddingTop in JSX as well as the object.

9. Conclusion

In this tutorial, we briefly touched many aspects of JSX. You should be comfortable writing JSX syntax. It is very helpful writing React components. Also, you may encounter the JSX while reading someone’s code. It is a good tool to have.