What is JSX in React, and is it worth making friends with it

What is JSX in React, and is it worth making friends with it

JSX is an XML/HTML-like syntax from React that extends ECMAScript. JSX allows you to write HTML code mixed with JavaScript. Take a look at the following example:

1export const App = () => {
2  return (
3    <main id="root">
4      <h1>Hello Folks!</h1>
5      <p>
6        Random question: 
7        Is <strong>FC Barcelona</strong> win any match in the Champions League this season? 
8        </p>
9    </main>
10  );
11}
12
13export default App;
14

Each JSX code is converted into the React.createElement function, which the web browser knows. Take a look at the converted code I showed you in a previous snippet:

1export const App = () => {
2  return React.createElement(
3    "main",
4    { id: "root" },
5    React.createElement(
6      "h1",
7      null,
8      "Hello Folks!"
9    ),
10    React.createElement(
11      "p",
12      null,
13      "Random question: Is ",
14      React.createElement(
15        "strong",
16        null,
17        "FC Barcelona"
18      ),
19      " win any match in the Champions League this season?"
20    )
21  );
22};
23
24export default App;
25

The react createElement function creates and returns a new React element. Here is the function signature:

1React.createElement(
2  type,
3  [props],
4  [...children]
5)
6

The type argument can be an HTML element or React element (or even React fragment). The second argument is the props object which contains HTML tag attributes or props of a React element. The last argument is children, and so this is another jsx element transformed to React createElement function.

In the above code, you can see there are nested elements. All jsx tags are transported to react createElement functions, and regular javaScript can understand them.

So if you ask what is jsx in React, what is jsx meaning, I may answer you that is a special syntax that allows mixing plain JavaScript and HTML elements to speed up development. Then you can ask...

Is JSX necessary for React?

It's not so if you don't like JSX syntax, or you want to write JavaScript code without configuring babel to transpioling JSX syntax to actual javascript code, you can write React apps without JSX.

Pro-tip for you then: if you want to avoid writing React.createElement too much, you can try something like this:

1const e = React.createElement;
2
3ReactDOM.render(
4  e('div', null, 'Are you sure you don't want to use JSX?'),
5  document.getElementById('root')
6);
7

React JSX Explained with Examples

React JSX is React's core concept. If you have a good understanding of it properly, then you can write React code efficiently. Let's see common use cases of JSX in React.

How do I add JavaScript code in JSX?

To add JSX-style code, you need to use curly brackets like this:

1export const App = () => {
2  const welcomeMessage = 'Hello folks!';
3
4  return (
5    <main id="root">
6      <h1>{welcomeMessage}</h1>
7    </main>
8  );
9}
10
11export default App;
12

JSX doesn't allow to render objects directly as a JSX tag, so this react code is not valid, and the error occurs when using JSX Expression when rendering an object.

1export const App = () => {
2  const welcomeMessage = {
3    text: 'Hello folks!'
4  };
5
6  return (
7    <main id="root">
8      <h1>{welcomeMessage}</h1>
9    </main>
10  );
11}
12
13export default App;
14

But you can write arrays in JSX Expressions because arrays are converted to strings while rendering. So this react' component is valid:

1export const App = () => {
2  const welcomeMessage = ['Hello', ' ',  'folks', '!'];
3
4  return (
5    <main id="root">
6      <h1>{welcomeMessage}</h1>
7    </main>
8  );
9}
10
11export default App;
12

Attributes

JSX allows you to use native HTML attributes and your own custom attributes as well. For native HTML attributes, JSX uses camel case convention instead of the normal HTML naming convention. Besides, please note that, for example, a class word is a reserved keyword and for either. For those keywords, JSX uses a className for a class and a htmlFor for a reserved keyword (for).

Custom HTML attributes in JSX

For custom HTML attributes, you must use a data prefix. It looks pretty the same as regular HTML.

1export const App = () => {
2  const welcomeMessage = ['Hello', ' ',  'folks', '!'];
3  const isCustom = true;
4
5  return (
6    <main id="root">
7      <h1 data-isCustom={isCustom}>{welcomeMessage}</h1>
8    </main>
9  );
10}
11
12export default App;
13

As you can see in that react component on <h1> HTML tag, I used the data-isCustom attribute and curly braces to pass value to the attribute. Moreover, you can pass values to attributes of HTML tags using string literals like this:

1export const App = () => {
2  const welcomeMessage = ['Hello', ' ',  'folks', '!'];
3
4  return (
5    <main id="root">
6      <h1 data-mode="default">{welcomeMessage}</h1>
7    </main>
8  );
9}
10
11export default App;
12

JavaScript Expressions

JavaScript expression may be used inside JSX. What is not surprising, I suppose, when you want to use a JavaScript expression, you need to wrap it by curly braces {}

If statements

You cannot use if-else statements in JSX. Instead, you can use conditional or JavaScript ternary expressions. Take a look at the simple React component with JSX if statement:

1export const App = () => {
2  const welcomeMessage = ['Hello', ' ',  'folks', '!'];
3  const shouldDisplay = true;
4
5  return (
6    <main id="root">
7      {shouldDisplay && <h1 data-mode="default">{welcomeMessage}</h1>}
8    </main>
9  );
10}
11
12export default App;
13

For if/else you can use something like this:

1{shouldDisplay ? <h1 data-mode="default">{welcomeMessage}</h1> : 'no way!'}
2

I prefer to explode JavaScript expressions to const (and sometimes memorize them using React useMemo hook because of performance reasons). Take a look at the JSX code below:

1export const App = (props) => {
2  const { hasError } = props;
3  const welcomeMessage = 'Hello folks!';
4  const errorMessage = 'Something went wrong.'
5
6  const shouldDisplayError = hasError ? 
7    <p>{errorMessage}</p> : <h1 >{welcomeMessage}</h1>;
8
9  return (
10    <main id="root">
11      {shouldDisplayError}
12    </main>
13  );
14}
15
16export default App;
17

Looping

When you want to render a JavaScript array using JSX, you can use something like this:

1export const App = () => {
2  const array = ['a', 'b', 'c']
3
4  return (
5    <main id="root">
6      {array.map(el => <p key={el}>This is {el}</p>)}
7    </main>
8  );
9}
10export default App;
11

Spread operator

The spread operator is not supported as a child jsx expression, so you are not able to put something like this to a react component:

1 {...['a','b','c']}
2

Comments in JSX code

If you want to insert a comment to the react component, you need to wrap its using curly braces.

1{/** this is comment */}
2

JSX Styling

React encourages to use of inline styles. You can use JSX expressions to pass value to the style attribute to set inline styles. React will also automatically append px following the number of the specified property.

Note: inline styling is not the only way to style react elements. There are a few other approaches, but this is the topic for another article.

JSX: Conclusion

When you work on the React application, you can use JSX to put markup into javascript code. That means that you have HTML tags and JavaScript expressions in the same file.

Each JSX tag is transformed to React createElement javascript function. Moreover, If you don't want to use JSX for any reason, you can write react code without JSX.

In my opinion, JSX has many advantages, and definitely, it's a friend of any React developer. I love it the most in JSX because it looks like JavaScript with more power (It's fair to say that JSX is built on top of JavaScript). I like that approach more than something you can find in Vue.js or Angular, where you need to learn specific framework functions and syntax.

jsx, react and JavaScript helps creating react code
About the author

Marcin Kwiatkowski

Frontend developer, Certified Magento Full Stack Developer, writer, based in Poland. He has eight years of professional Software engineering experience. Privately, husband and father. He likes reading books, drawing, and walking through mountains.

Read more