React JSX

14-Apr-2024

React JSX

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.

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;
In this example above:

  • <div>: Represents a container element.
  • <h1>: Represents a heading.
  • <p>: Represents a paragraph.

Embedding JavaScript Expressions

You can embed JavaScript expressions inside curly braces {} within JSX tags.

const name = "John";
const greeting = <p>Hello, {name}!</p>; ReactDOM.render( greeting, document.getElementById('root') );
In this example, the value of the name variable is inserted into the JSX expression.

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.

import 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;
JSX Attributes

You can also use JSX attributes to specify props for React elements.


const link = <a href="https://tutorialb.com">Click me!</a>;
In this example, href is an attribute of the <a> element.

JSX and Events

You can attach event handlers to JSX elements.

const handleClick = () => { console.log('Button clicked!'); }; const button = <button onClick={handleClick}>Click me!</button>;
In this example, the onClick attribute is used to specify a click event handler for the <button> element.

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>;
This spreads all properties of the `props` object onto the <button> element.

That's a basic rundown of JSX with React, covering its syntax, usage, embedding JavaScript expressions, attributes, events, and spread attributes.

Comments