JSX (JavaScript XML) is a syntax extension for JavaScript that allows developers to write HTML-like code directly within JavaScript files. It is one of the core features of React, enhancing the development experience by enabling a clear and concise way to describe the structure of user interfaces (UI).
Here’s everything you need to know about JSX:
JSX allows you to write XML-like tags that represent HTML elements or React components within JavaScript. While JSX looks like HTML, it’s not—under the hood, JSX is compiled into standard JavaScript using tools like Babel.
const Greeting = () => { return <h1>Hello, World!</h1>; };
const Greeting = () => { return React.createElement('h1', null, 'Hello, World!'); };
You can embed JavaScript expressions within JSX by wrapping them in curly braces {}.
const name = "Alice"; const Greeting = () => <h1>Hello, {name}!</h1>;
JSX supports attributes similar to HTML but with camelCase naming for properties.
const Button = () => <button className="btn" onClick={() => alert('Clicked!')}>Click Me</button>;
You can nest elements inside one another to create a complete UI structure.
const App = () => ( <div> <h1>Welcome</h1> <p>This is a nested JSX structure.</p> </div> );
Use JavaScript logic to conditionally render elements.
const isLoggedIn = true; const App = () => ( <div> {isLoggedIn ? <h1>Welcome Back!</h1> : <h1>Please Log In</h1>} </div> );
JSX provides a declarative way to define the UI, making the code more readable and closer to the actual UI design.
Since JSX is just syntactic sugar for JavaScript functions, it allows seamless integration of logic, state, and props within your UI definitions.
JSX makes the UI code easier to write, understand, and debug compared to traditional React.createElement() calls.
JSX must return a single root element. Use a
const Greeting = () => { return <h1>Hello, World!</h1>; };
For elements without children, use self-closing tags.
const Greeting = () => { return React.createElement('h1', null, 'Hello, World!'); };
Although JSX supports inline styling via the style attribute, use CSS-in-JS libraries or external stylesheets for better maintainability.
const name = "Alice"; const Greeting = () => <h1>Hello, {name}!</h1>;
JSX automatically escapes dangerous inputs to prevent XSS attacks. For example: