Getting Started with JSX

Getting Started with JSX

A Comprehensive Guide to Writing Efficient and Effective Code in React

const myComponent = <h1>Hello, I am sample JSX</h1>;

The above code snippet somewhat looks like HTML and it also uses a JavaScript-like variable but is neither HTML nor JavaScript, it is JSX.

What is JSX?

JSX (JavaScript XML), originally developed by Facebook for use with its React library, is a syntax extension for JavaScript. It allows you to write HTML-like code within your JavaScript code.

JSX makes it easier to write code that looks and behaves similar to HTML but still have access to the full power of JavaScript. It acts as a visual aid when working with UI inside the JavaScript code. It also allows React to show more useful error and warning messages.

Why JSX?

React.createElement was the original syntax for creating React elements. Earlier developers had to write HTML-like code using strings of JavaScript, which was often difficult to read and maintain.

This is why JSX was introduced. It's a way to write React components using a more HTML-like syntax, making it easier to read and write than using the React.createElement() method..

Here's an example of React code using createElement and JSX:

React.createElement:

import React from 'react';

const MyApp = () => {
  return React.createElement('div', { className: 'react-demo' },
    React.createElement('h1', null, 'What are we learning today?'),
    React.createElement('p', null, 'We are not learning to use React without JSX.')
  );
};

export default MyApp;

JSX:

import React from 'react';

const MyApp = () => {
  return (
    <div className="react-demo">
      <h1>What are we learning today?</h1>
      <p>We are learning to use React with JSX.</p>
    </div>
  );
};

export default MyApp;

As you can see, the JSX version is easier to read and write, although both examples will render the same result.

JSX is actually transpiled to JavaScript by tools like Babel before it is used by the browser, so it still ends up using React.createElement() behind the scenes. Although not mandatory, the above example is the very reason JSX is recommended for writing React applications.

JSX is easier to read, write, and maintain than plain JavaScript code.

Let's discuss the basics of JSX and how to use it in React.

Rules of using JSX:

🔥One Parent Element

The HTML code must be wrapped in ONE Parent element.

Suppose you want to return multiple elements from a component. You must wrap them inside a parent element, like a div element.

const MyApp = (
  <div>
    <h1>Coding JSX</h1>
    <p>JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement()  and/or appendChild() methods.</p>
  </div>
);

JSX will throw an error if the HTML is not correct, or if the HTML misses a parent element.

Alternatively, you can use a fragment to wrap multiple lines. This will prevent unnecessarily adding extra nodes to the DOM.

A fragment looks like an empty HTML tag: <> </>.

const MyApp = (
  <>
    <h1>Coding JSX</h1>
    <p>JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement()  and/or appendChild() methods.</p>
  <>
);

🔥Elements Must be Closed

Unlike some HTML elements that do not have a closing tag, JSX follows XML rules. Therefore, in React, HTML elements must be properly closed.

JSX will throw an error if the HTML is not properly closed.

Example: Self-closing tags like <img> should be written as <img/>.

const MyApp = <input type="text" />;

🔥Using camelCase

JSX uses camelCase naming convention for attributes rather than the standard naming convention of HTML.

The class attribute is a frequently used attribute in HTML. However it is a reserved keyword in JavaScript, and you are not allowed to use it in JSX.

To address this issue, JSX uses the className attribute instead. When JSX is rendered, JSX className attributes are automatically rendered as class attributes.

const MyApp = <h1 className="myclass">JSX uses camelCase naming convention.</h1>;

🔥Writing JSX Expressions

With JSX you can write expressions inside curly braces { }.
Content between the opening and closing curly braces will be evaluated as JavaScript. JSX will execute the expression within the braces and return the result:

  • If you want to execute the expression 50 + 50:
const MyApp = <h1>React is {50 + 50} times better with JSX</h1>;

🔥if-else statements inside jsx

You cannot use if-else statements inside JSX.

To be able to use conditional statements in JSX, you can do the following:

  • Use ternary expressions :

Write "Welcome back!" if isLoggedIn is true, otherwise "Please log in":

const isLoggedIn = true;

return (
  <div>
    {isLoggedIn ? (
      <p>Welcome back!</p>
    ) : (
      <p>Please log in.</p>
    )}
  </div>
);

🔥JSX Comments

To write comments in JSX, begin with /* and end with */ and wrap them in curly braces {} just like in the case of JSX expressions.

Let's see an example:

import React from 'react';

const MyApp = () => {
  return (
    <div>  
      <h1 className="hello">Is this a valid comment?</h1>  
       // This is not a valid comment
       /* Not this either! */
      {/* This is a valid comment in JSX */}   
    </div>  
  );
}

export default MyApp;

Advantages of using JSX

  • It is faster than regular JavaScript because it performs optimization while translating the code to JavaScript.

  • It helps in improving the readability of the code and can be very helpful when working on large, complex projects.

  • It is type-safe, and most of the errors can be found at compilation time.

  • It makes it easier to create templates.

  • It makes it easier to create dynamic, interactive user interfaces.

To Summarize

JSX is widely used in React applications and offers several advantages over traditional JavaScript-based approaches for building user interfaces. Improved readability, maintainability, and the ability to catch errors during compilation are some of the benefits of using JSX.

However, it's worth noting that there are some rules and best practices to follow when you're working with JSX, like using camelCase naming conventions for HTML attributes

In summary, JSX is a valuable tool for developers working with React and offers a wide range of benefits to create more robust and maintainable applications.


References


Thank you for taking the time to read this blog. Hope you found it informative and enjoyable! Stay tuned for future articles and be sure to follow along.

In the next article of this series, we shall take a look at Components.

Catch you guys on the next one. Cheers .. ✌️

Did you find this article valuable?

Support Raj Sarkar by becoming a sponsor. Any amount is appreciated!