JSX stands for JavaScript XML. JSX is used to write the HTML-like code in JavaScript.
JSX is basically a syntax extension of JavaScript. React JSX helps us to write HTML in JavaScript and forms the basis of React Development. Using JSX is not compulsory but it is highly recommended for programming in React as it makes the development process easier as the code becomes easy to write and read.
Below is a simple example of JSX syntax used in a React component
JavaScript
import React from "react";
const HelloWorld = () => {
return <h1>Hello, World!</h1>;
};
export default HelloWorld;
- The HelloWorld component uses JSX to render an h1 element.
- The <h1> tag is returned directly, showing how HTML-like syntax can be embedded in JavaScript.
1. Embedding JavaScript Expressions in JSX
JSX allows JavaScript expressions to be embedded using {}.
JavaScript
import React from "react";
const Greeting = ({ name }) => {
return <h2>Welcome, {name ? name : "Guest"}!</h2>;
};
export default Greeting;
- You can embed JavaScript expressions in JSX using {}.
- The name prop is dynamically displayed. If name is absent, it defaults to “Guest”.
2. JSX is an Expression Too
JSX can be assigned to variables, passed as arguments, or returned from functions.
JavaScript
const element = <h1>JSX is just an expression!</h1>;
const App = () => element;
JSX works like any other JavaScript expression.
3. Specifying Attributes with JSX
JSX uses attributes similar to HTML but sticks to JavaScript conventions.
JavaScript
const ProfilePicture = () => {
return <img src="profile.jpg" alt="Profile" width="150" />;
};
Use camelCase for attribute names like className, htmlFor, and tabIndex.
4. Specifying Children with JSX
Elements can have children nested directly within them.
JavaScript
const Greeting = () => {
return (
<div>
<h1>Hello!</h1>
<p>Welcome to our website.</p>
</div>
);
};
JSX supports nested elements as children, making component structures intuitive.
5. JSX Prevents Injection Attacks
JSX escapes values before rendering them, preventing injection attacks.
JavaScript
const userInput = "<img src=x onerror=alert(1)>";
const SafeContent = () => <div>{userInput}</div>;
The above userInput is rendered as plain text, ensuring security.
6. JSX Represents Objects
Every JSX element is converted to a JavaScript object.
JavaScript
const element = <h1>Hello, JSX!</h1>;
console.log(element);
The element above is an object with properties like type, props, and children.
Additional JSX Examples
1. Conditional Rendering
JavaScript
import React from "react";
const UserStatus = ({ isLoggedIn }) => {
return <p>{isLoggedIn ? "Logged In" : "Please Log In"}</p>;
};
export default UserStatus;
- JSX supports conditional rendering with the ternary operator.
- The isLoggedIn prop determines the displayed message.
2. Looping in JSX
JavaScript
import React from "react";
const ItemList = ({ items }) => {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
};
export default ItemList;
- You can use Array.map() to dynamically render lists.
- A unique key is required for each list item to ensure React optimizes updates.
3. Using Inline Styles
JavaScript
import React from "react";
const StyledBox = () => {
const boxStyle = { border: "1px solid black", padding: "10px" };
return <div style={boxStyle}>This is a styled box.</div>;
};
export default StyledBox;
- Inline styles in JSX use a JavaScript object with camelCase properties.
- The style attribute accepts this object to style the element.
4. Passing Attributes
JavaScript
import React from "react";
const ProfilePicture = () => {
return <img src="profile.jpg" alt="Profile" width="150" />;
};
export default ProfilePicture;
- HTML attributes like src and alt are written directly in JSX.
- Boolean attributes (like disabled) are written as disabled={true} or simply disabled.
5. Nested Components
JavaScript
import React from "react";
const Header = () => <h1>Welcome to My App</h1>;
const Footer = () => <footer>ÂĐ 2024 My App</footer>;
const App = () => {
return (
<div>
<Header />
<p>This is the main content.</p>
<Footer />
</div>
);
};
export default App;
- JSX allows you to reuse components like <Header /> and <Footer />.
- This demonstrates how JSX supports composable UI design.
JavaScript Developers Transitioning to JSX
If you are transitioning from JavaScript to React JSX, here are some key differences and rules to keep in mind:
1. Closing Tags
All elements in JSX must have a closing tag. Self-closing tags like <img /> or <br /> are mandatory.
// Incorrect
<img>
// Correct
<img />
2. Use className Instead of class
Since class is a reserved keyword in JavaScript, JSX uses className for defining CSS classes.
<div className="container"></div>
3. Inline Styles Use JavaScript Objects
Styles in JSX must be passed as objects with camelCase property names.
const style = { backgroundColor: "blue", color: "white" };
<div style={style}>Styled Element</div>;4. JavaScript Expressions in JSX
Embed any JavaScript expression within {} in JSX.
const value = 42;
<p>The answer is {value}.</p>;5. Parent Element Requirement
JSX expressions must return a single parent element. Use <React.Fragment> or <> for multiple elements.
// Incorrect
return <h1>Title</h1><p>Subtitle</p>;
// Correct
return (
<>
<h1>Title</h1>
<p>Subtitle</p>
</>
);6. Event Handlers
Event handlers in JSX use camelCase and receive a function as the value.
<button onClick={() => alert("Clicked!")}>Click Me</button>;React JSX – FAQs
Can I use JSX without React?
JSX is specifically designed for React and requires React libraries to work.
What happens if I don’t use a key in lists?
React will warn about missing keys, and updates may behave unpredictably.
Is JSX faster than plain JavaScript?
No, JSX is transpiled to JavaScript, so thereâs no inherent performance difference.
Can I use JavaScript functions in JSX?
Yes, you can call JavaScript functions or use expressions directly within {}.
What are fragments in JSX?
Fragments (<> </>) let you group elements without adding an extra DOM node.