What is JSX?
JSX (JavaScript XML) is a syntax extension for JavaScript commonly used with React, a popular JavaScript library for building user interfaces. JSX allows developers to write HTML-like syntax within JavaScript, which React can then transform into DOM elements.
Instead of separating HTML and JavaScript like traditional web development, JSX allows you to combine the two, making it easier to write and understand UI components. JSX code is transpiled into regular JavaScript using tools like Babel before being executed in the browser.
Basic Example of JSX
const element = <h1>Hello, World!</h1>;
In the example above, the JSX syntax looks similar to HTML, but it's actually JavaScript. React will convert this into a function that creates a DOM element like this:
const element = React.createElement('h1', null, 'Hello, World!');
Full Example of a JSX Component
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
const element = <Welcome name="John" />;
ReactDOM.render(element, document.getElementById('root'));
Output:
The above JSX will render this in the browser:
Hello, John!
Key Points of JSX:
- HTML-like Syntax: JSX resembles HTML but is transformed into JavaScript.
- Embedding Expressions: You can embed any JavaScript expression inside curly braces
{}
in JSX. - Must Return a Single Element: JSX expressions must have one root element. If needed, you can use a
div
or React Fragment (<> </>
) to wrap multiple elements. - Attributes in JSX: JSX attributes are written in camelCase for JavaScript reserved words (e.g.,
className
instead ofclass
,onClick
instead ofonclick
).
Example with JSX Attributes
const element = <button className="btn" onClick={handleClick}>Click me</button>;
Here, className
is used instead of class
, and onClick
refers to a JavaScript function that handles the button click.
Final Note:
JSX makes code simpler and more intuitive when building React applications, but remember that it is not mandatory in React. You could always write your React components without JSX, though it would be more verbose and harder to read.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.