JSX (JavaScript XML) is an extension of JavaScript syntax used in React to write declarative and component-based UI code. It allows you to define and embed HTML-like code directly within your JavaScript code.
JSX resembles HTML syntax, but it is not actually HTML. It gets transformed into regular JavaScript function calls during the compilation process. Here’s an example of JSX code:
import React from 'react';
function MyComponent() {
return (
<div className="my-component">
<h1>Hello, JSX!</h1>
<p>This is a JSX paragraph.</p>
</div>
);
}
export default MyComponent;
In this example, the MyComponent
function is a React component that returns JSX code. Inside the return
statement, we define a <div>
element with the className
attribute set to “my-component”. We also have an <h1>
element and a <p>
element nested inside the <div>
.
JSX allows you to use JavaScript expressions within curly braces {}
to incorporate dynamic values or execute JavaScript logic. For example:
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
In this case, the props.name
expression is dynamically inserted within the JSX, allowing you to display a personalized greeting based on the name
prop passed to the component.
JSX helps in writing readable and intuitive code, combining HTML-like structure and JavaScript functionality in a single syntax. It is transformed into regular JavaScript function calls, making it compatible with existing JavaScript tools and libraries.