JSX is a syntax extension for JavaScript that looks similar to HTML. In JSX, you can write HTML-like tags directly in your JavaScript code. It allows you to write more concise and readable code.
In this example above:import React from 'react'; // Define a functional component const MyComponent = () => { return ( <div> <h1>Hello, JSX!</h1> <p>This is a paragraph written in JSX.</p> </div> ); } export default MyComponent;
Embedding JavaScript Expressions
You can embed JavaScript expressions inside curly braces {} within JSX tags.
In this example, the value of the name variable is inserted into the JSX expression.const name = "John";const greeting = <p>Hello, {name}!</p>; ReactDOM.render( greeting, document.getElementById('root') );
Using JSX in React Components
JSX is commonly used in React to describe what the UI should look like. You can use JSX in React components just like in regular JavaScript files.
JSX Attributesimport React from 'react'; const MyComponent = () => { const name = "Alice"; return ( <div> <h1>Hello, {name}!</h1> <p>This is a paragraph written in JSX.</p> </div> ); } export default MyComponent;
You can also use JSX attributes to specify props for React elements.
In this example, href is an attribute of the <a> element.const link = <a href="https://tutorialb.com">Click me!</a>;
JSX and Events
You can attach event handlers to JSX elements.
In this example, the onClick attribute is used to specify a click event handler for the <button> element.const handleClick = () => { console.log('Button clicked!'); }; const button = <button onClick={handleClick}>Click me!</button>;
JSX Spread Attributes
JSX supports spread attributes, which allow you to pass all props of an object as attributes to an element.
const props = { className: 'btn btn-primary', onClick: handleClick, }; const button = <button {...props}>Click me!</button>;