Lesson 2 - JSX

2.1 - What Is JSX

JSX or JavaScript XML is a syntax extension for JavaScript that allows you to write HTML-like code within JavaScript. It is used extensively in React to describe what the UI should look like. While it may look like HTML, it is a combination of JavaScript and XML.

Why We Use JSX in React?

JSX makes the code easier to understand by allowing you to write UI components using a syntax that looks similar to HTML. It allows you to write declarative code, meaning you can describe what the UI should look like and React takes care of rendering it. This approach contrasts with imperative code, where you would need to manually manipulate the DOM.

JSX allows you to embed JavaScript expressions directly within your markup, providing powerful features like dynamic rendering and logic handling within the UI. For example, you can easily display data from variables or use conditional rendering within your JSX code, making your components more powerful and flexible.

That's not all.

Modern development tools, like Babel, can convert JSX into standard JavaScript, making it compatible with all browsers. This tooling support streamlines the development process and allows you to leverage the full power of JSX without worrying about browser compatibility.

JSX Syntaxes JSX syntaxes are very similar to HTML, making it easy to learn and use. JSX uses HTML-like tags to create elements. Attributes in JSX are written similarly to HTML. However, when you have multi-word attributes, you have to follow the camelCase.

What's camelCase? Let's learn this with an example.

In HTML, we use the class attribute to assign a class to a DOM element. However, in JSX, class is a reserved keyword, which can lead to runtime errors. To avoid this, simply use className instead of class.

There are a few differences between JSX and HTML.

Class Attribute: In HTML, you use class to define CSS classes, but in JSX, you use className because class is a reserved keyword in JavaScript. This can cause errors sometimes. For example,

const element = <div className="my-class">Content</div>;

Self-Closing Tags: Just like in HTML, you can use self-closing tags in JSX. However, in JSX, you must explicitly close the tag. Here is a quick example,

const element = <img src="image.png" alt="My Image" />;