JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code directly within JavaScript. JSX makes it easier to create React components and visualize the structure of your user interface (UI).
1. What is JSX?
JSX is not a requirement for React, but it’s widely used because it simplifies coding. JSX is converted into JavaScript using tools like Babel. For example:
JSX Code:
const element = <h1>Hello, React!</h1>;
Compiled JavaScript:
const element = React.createElement('h1', null, 'Hello, React!');
2. Writing JSX
Basic JSX Syntax
JSX looks like HTML but is embedded within JavaScript. You can include elements like <div>
, <h1>
, and <p>
inside JSX.
Example:
const element = <h1>Welcome to React!</h1>; ReactDOM.render(element, document.getElementById('root'));
Embedding JavaScript in JSX
You can use curly braces {}
to embed JavaScript expressions inside JSX.
Example:
const name = "React"; const element = <h1>Welcome, {name}!</h1>; ReactDOM.render(element, document.getElementById('root'));
Using Functions in JSX
You can call JavaScript functions directly within JSX.
Example:
function greet(user) { return `Hello, ${user}!`; } const element = <h1>{greet("React Developer")}</h1>; ReactDOM.render(element, document.getElementById('root'));
3. JSX Attributes
JSX attributes are similar to HTML attributes but use camelCase naming conventions.
Example:
const element = <img src="logo.png" alt="React Logo" />; ReactDOM.render(element, document.getElementById('root'));
Special Attribute Differences
- Use
className
instead ofclass
for CSS classes. - Use
htmlFor
instead offor
for labels.
Example:
const element = <label htmlFor="nameInput">Name:</label>;
4. JSX with Multiple Elements
In JSX, you cannot return multiple sibling elements directly. Wrap them in a parent element or use a React Fragment.
Using a Parent Element:
const element = ( <div> <h1>Hello, React!</h1> <p>This is a paragraph.</p> </div> ); ReactDOM.render(element, document.getElementById('root'));
Using React Fragments:
const element = ( <> <h1>Hello, React!</h1> <p>This is a paragraph.</p> </> ); ReactDOM.render(element, document.getElementById('root'));
5. JSX Styling
JSX supports inline styles written as objects with camelCase property names.
Example:
const style = { color: 'blue', backgroundColor: 'lightgray', padding: '10px', fontFamily: 'Arial' }; const element = <h1 style={style}>Styled with JSX</h1>; ReactDOM.render(element, document.getElementById('root'));
6. JSX Conditionals
Use JavaScript logic (e.g., ternary operators) for conditional rendering in JSX.
Example:
const isLoggedIn = true; const element = ( <div> {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in.</h1>} </div> ); ReactDOM.render(element, document.getElementById('root'));
7. JSX Loops
You can use the .map()
function to render lists in JSX.
Example:
const items = ['Apple', 'Banana', 'Cherry']; const element = ( <ul> {items.map((item, index) => ( <li key={index}>{item}</li> ))} </ul> ); ReactDOM.render(element, document.getElementById('root'));
8. JSX Comments
Use {/* Comment */}
for inline comments within JSX.
Example:
const element = ( <div> {/* This is a comment */} <h1>Hello, React!</h1> </div> ); ReactDOM.render(element, document.getElementById('root'));
9. JSX Rules
- Parent Element: JSX must have a single parent element.
- Correct:
return ( <div> <h1>Hello</h1> <p>Welcome!</p> </div> );
- Incorrect:
return ( <h1>Hello</h1> <p>Welcome!</p> );
- Correct:
- Close All Tags: All tags must be properly closed, including self-closing tags.
- Correct:
<img src="logo.png" alt="React Logo" />
- Incorrect:
<img src="logo.png" alt="React Logo">
- Correct:
- Use CamelCase for Attributes: Attributes must use camelCase for consistency.
- Correct:
tabIndex
,onClick
- Incorrect:
tabindex
,onclick
- Correct:
- Do Not Use Reserved Words: Avoid using reserved words like
class
andfor
. UseclassName
andhtmlFor
instead.
10. JSX with Expressions
JSX can handle complex expressions, but always return valid JSX elements.
Example:
const a = 5, b = 10; const element = <h1>The sum is: {a + b}</h1>; ReactDOM.render(element, document.getElementById('root'));
11. Dangerous HTML Rendering
If you need to inject raw HTML, use the dangerouslySetInnerHTML
attribute. Use with caution!
Example:
const rawHTML = { __html: '<h1 style="color: red;">Hello, Raw HTML!</h1>' }; const element = <div dangerouslySetInnerHTML={rawHTML}></div>; ReactDOM.render(element, document.getElementById('root'));
12. JSX and React Components
JSX is commonly used in React components for rendering UI.
Example: Functional Component:
function Welcome() { return <h1>Welcome to React!</h1>; } ReactDOM.render(<Welcome />, document.getElementById('root'));
Key Points to Remember
- JSX simplifies the process of writing React components.
- JSX is not valid JavaScript—it’s transpiled to
React.createElement()
by Babel. - Always return a single parent element in JSX.
- Use curly braces
{}
to include JavaScript logic. - Use camelCase for attributes and avoid reserved words like
class
andfor
.
By mastering JSX, you can efficiently create React components and structure your application’s UI in a readable and declarative way.