JSX (JavaScript XML) is a syntax extension used in React for creating and rendering components. It allows you to write HTML-like code within JavaScript, making it easier to define the structure and appearance of your UI components. JSX is not mandatory in React, but it is a popular choice due to its simplicity and readability.
Here’s an explanation of JSX with examples:
Basic JSX Syntax:
JSX looks similar to HTML but is actually JavaScript. It allows you to use HTML tags and components in your code.
const element = <h1>Hello, Abhishek!</h1>;
In the example above, we define a JSX element using angle brackets ( and). The content within the tags is treated as text.
Embedding Expressions:
JSX allows you to embed JavaScript expressions within curly braces {}.
const name = 'abhishek';
const element = <h1>Hello, {name}!</h1>;
In this example, the value of the name variable is embedded within the JSX element.
Using JSX with JavaScript Functions:
JSX can be used with JavaScript functions to define components.
function Greeting() {
return <h1>Hello, Abhishek!</h1>;
}
Here, we define a functional component Greeting that returns a JSX element.
JSX Elements and Attributes: JSX allows you to define custom HTML-like tags and assign attributes to them.
const element = <img src="image.jpg" alt="Image" />;
In this example, we create an img tag with src and alt attributes.
JSX and Component Composition: JSX allows you to compose multiple components together.
function Greeting() {
return <h1>Hello, Abhishek!</h1>;
}
function App() {
return (
<div>
<Greeting />
<p>Welcome to my app.</p>
</div>
);
}
Here, we define a component App that renders the Greeting component along with a p tag
I’m Abhishek, a DevOps, SRE, DevSecOps, and Cloud expert with a passion for sharing knowledge and real-world experiences. I’ve had the opportunity to work with Cotocus and continue to contribute to multiple platforms where I share insights across different domains:
-
DevOps School – Tech blogs and tutorials
-
Holiday Landmark – Travel stories and guides
-
Stocks Mantra – Stock market strategies and tips
-
My Medic Plus – Health and fitness guidance
-
TrueReviewNow – Honest product reviews
-
Wizbrand – SEO and digital tools for businesses
I’m also exploring the fascinating world of Quantum Computing.