JSX (JavaScript XML) is a syntax extension for Javascript that allows us to write XML or HTML-like code within our Javascript files.
JSX is often associated with React, but it is a standalone syntax that can be used with other libraries or frameworks.
React is a Javascript library for building user interfaces, as it provides a more readable and expressive way to define UI components.
JSX allows us to embed HTML-like code directly within Javascript.
JSX makes it easy to write and understand the structure of our user interface.
const paragraphElement = <p>Hello, JSX!</p>; return paragraphElement;
const uiElement = ( <div> <h3>Hello World!</h3> <article>This is a Article.</article> </div> ); return uiElement;
JSX is more expressive than plain Javascript when defining UI components. It resembles HTML, making it easier to visualize the structure of the rendered output.
const fullName = "Alice Collin"; const uiElement = <h2>Hi, {fullName}!</h2>; return uiElement;
let value = ""; const handleOnChange = (e) => { value += e.target.value; }; const uiElement = <input onChange={(e) => handleOnChange(e)} value={value} />; return uiElement;
JSX allows embedding Javascript expressions within curly braces {}. This enables dynamic content and expressions to be included in the markup.
const CustomComponent = () => <h3>custom component</h3>; const uiElement = ( <div> <h1>Hello, JSX with Components!</h1> <CustomComponent /> </div> ); return uiElement;
JSX allows us to use conditional statements to render different content based on conditions.
const isLoggedIn = true; const uiElement = ( <p> {isLoggedIn ? <h3>Welcome, User!</h3> : <h3>Page Not Found</h3>} </p> );
JSX attributes are similar to HTML attributes but use camelCase naming conventions.
Event handlers are also specified using camelCase.
// JSX Syntax const uiElement = <h3>Hi, JSX!</h3>; // Babel-transformed const uiElement = React.createElement('h3', null, 'Hi, JSX!');
JSX allows us to use React components within its syntax. Components can be created and used just like HTML tags.
// JSX Syntax const uiElement = () => { return( <> <h3>Hi, JSX!</h3> <p>This is Paragraph!!</p> </> ) } // Or using Fragments Tag const uiElement = () => { return( <React.Fragment> <h3>Hi, JSX!</h3> <p>This is Paragraph!!</p> </React.Fragment> ) }
JSX elements must have a single root element.
Fragments allow us to group multiple elements without introducing an additional parent element.
JSX is not natively understood by browsers. It needs to be transpiled by tools like Babel into standard JavaScript.