JSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, it’s actually a syntax extension for JavaScript.
What is JSX?
JSX combines HTML and JavaScript in a single syntax, allowing you to create UI components in React. It simplifies rendering dynamic content by embedding JavaScript expressions inside HTML-like tags.
Syntax:
const element = <h1>Hello, world!</h1>;
- <h1>Hello, world!</h1> is a JSX element, similar to HTML, that represents a heading tag.
- JSX is converted into JavaScript behind the scenes, where React uses React.createElement() to turn the JSX code into actual HTML elements that the browser can understand.
How JSX Works
When React processes this JSX code, it converts it into JavaScript using Babel. This JavaScript code then creates real HTML elements in the browser’s DOM . which is how your web page gets displayed.
JSX Transformation Process
- Writing JSX: Write JSX just like HTML inside JavaScript files (React components).
const element = <h1>Hello, World!</h1>;
- JSX Gets Transformed: JSX is not directly understood by browsers. So, it gets converted into JavaScript by a tool called Babel. After conversion, the JSX becomes equivalent to React.createElement() calls. After transformation JSX becomes.
const element = React.createElement('h1', null, 'Hello, World!');
- React Creates Elements: React takes the JavaScript code generated from JSX and uses it to create real DOM elements that the browser can render on the screen.
How to Implement JSX in Action
JSX can be implemented in a React project to create dynamic and interactive UI components. Here are the steps to use JSX in a React application:
- Create a React App: If you don’t have a React app yet, create one using Create React App:
npx create-react-app jsx-example
cd jsx-example
npm start
- Write JSX in the Component: In the src/App.js file, write JSX to display a message:
JavaScript
import React from "react";
function App() {
const message = "Hello, JSX works!";
return <h1>{message}</h1>;
}
export default App;
Output:
- The JSX code <h1>{message}</h1> will be transformed into JavaScript by Babel. Then react will then create a virtual DOM element for the <h1> tag with the text inside. and this virtual DOM is then used to update the actual browser DOM, displaying "Hello, JSX works!" on the screen.
- After React processes the JSX, it renders the message on the screen.
Uses of JSX
Here are some significant uses of JSX:
1. Embedding Expressions
JSX allows you to embed JavaScript expressions directly within the HTML-like syntax. You can use curly braces {} to insert JavaScript expressions.
JavaScript
const name = 'Jonny';
const greeting = <h1>Hello, {name}!</h1>;
In this code
- {name} in JSX dynamically inserts the value of the name variable into the rendered output.
- JSX allows embedding JavaScript expressions, enabling dynamic content to be rendered within the UI.
2. Using Attributes in JSX
In JSX, attributes are specified similarly to HTML, but with some differences. Since JavaScript is used alongside JSX, certain attribute names are written in camelCase instead of the lowercase syntax used in HTML.
JavaScript
const element = <img src="" alt="A description" />;
- CamelCase for Attribute Names: In JSX, some HTML attributes are written in camelCase.
- For example, class becomes className, for becomes htmlFor, and style is an object.
- This is because class and for are reserved words in JavaScript.
3. Passing Children in JSX
In JSX, components or elements can accept children just like HTML elements. Children are nested elements or content that are passed into a component. This allows for flexible and reusable components.
JavaScript
const Welcome = (props) => {
return <div>{props.children}</div>;
};
const App = () => {
return (
<Welcome>
<h1>Hello, World!</h1>
<p>Welcome to React.</p>
</Welcome>
);
};
In this code
- Children as Props: The Welcome component does not explicitly define the content inside it. Instead, it uses {props.children} to render any child elements that are passed between the opening and closing tags of the component when it is used.
- Flexibility: The App component passes two child elements (<h1> and <p>) to Welcome. By using {props.children}, the Welcome component can render any child content, making it reusable with different content each time it’s used.
4. JSX Represents Objects
JSX is not directly rendered as HTML by React; instead, it gets compiled into JavaScript objects representing virtual DOM elements. These objects are later used by React to efficiently update the real DOM.
JavaScript
const element = React.createElement(
"button",
{
className: "btn",
onClick: () => alert("Clicked!"),
},
"Click Me"
);
The JSX code is converted into a JavaScript object
C++
{
type: 'button',
props: {
className: 'btn',
onClick: () => alert('Clicked!'),
children: ['Click Me']
}
}
In this code
- type: 'button': Defines the element type (button).
- props: Contains attributes like:
- className: 'btn': For styling.
- onClick: () => alert('Clicked!'): Event handler for click.
- children: ['Click Me']: Content inside the button.
- React converts JSX into a JavaScript object to efficiently render and manage the UI.
Why Use JSX in React
JSX provides several advantages when working with React:
- Declarative UI: JSX allows you to write HTML-like code directly in your JavaScript files. This makes it easier to visualize how your components will render and simplifies the UI development process.
- Cleaner Syntax: JSX is cleaner and more concise than manually using React.createElement() for each element. It reduces the amount of boilerplate code and makes components more readable.
- Dynamic Content: JSX makes it easy to embed dynamic content within your UI. JavaScript expressions can be placed inside {} within JSX tags, allowing for dynamic rendering of data and content.
Conclusion
JSX is a powerful feature of React that allows you to write HTML-like code within JavaScript. It simplifies the process of building user interfaces by combining the flexibility of JavaScript with the structure of HTML. JSX makes it easier to render dynamic content, embed expressions, and manage event handling. React efficiently converts JSX into JavaScript objects, which are used to update the real DOM.
Similar Reads
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability.It is developed and maintained by Facebook.The latest version of React is React 19.Uses
8 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.We will discuss the following approaches to setup environment in React.Table of Content
3 min read
React JS ReactDOMReactDom is a core react package that provides methods to interact with the Document Object Model or DOM. This package allows developers to access and modify the DOM. Let's see in brief what is the need to have the package. Table of ContentWhat is ReactDOM ?How to use ReactDOM ?Why ReactDOM is used
3 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
6 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are different from DOM elements as React elements are simple JavaScript objects and are effic
3 min read
React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite
5 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. In this article, we'll explore ReactJS keys, understand their importance, how the
5 min read
Components in React
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.What are Reactjs Functio
5 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
4 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he
5 min read
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects