JSX (JavaScript XML) is a syntax extension for JavaScript used in React to describe what the UI should look like. It allows you to write HTML-like code within JavaScript, making the code more readable and expressive. JSX combines the power of JavaScript with the familiarity of HTML, enabling you to build user interfaces with ease.
Basic Syntax:
const element = <h1>Hello, world!</h1>;
Embedding Expressions:
{}
. This allows you to dynamically insert values or perform computations.const name = 'John';
const greeting = <h1>Hello, {name}!</h1>;
Attributes:
class
becomes className
, and for
becomes htmlFor
.const element = <input type="text" placeholder="Enter your name" />;
Children:
const element = (
<div>
<h1>Hello, world!</h1>
<p>Welcome to JSX.</p>
</div>
);
Conditionals:
const isLoggedIn = true;
const element = (
<div>
{isLoggedIn ? <p>Welcome back!</p> : <p>Please sign up.</p>}
</div>
);
Lists:
map()
. This is useful for rendering dynamic lists.const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
<li key={number}>{number}</li>
);
const element = <ul>{listItems}</ul>;
Function Components:
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
const element = <Welcome name="Sara" />;
JavaScript Expressions in JSX:
const user = { firstName: 'John', lastName: 'Doe' };
const element = <h1>{`Hello, ${user.firstName} ${user.lastName}`}</h1>;
Preventing XSS:
JSX is not valid JavaScript by itself, so it needs to be compiled into JavaScript before it can be executed in a browser. This is typically done using a tool like Babel. For example, the JSX:
const element = <h1>Hello, world!</h1>;
is compiled into:
const element = React.createElement('h1', null, 'Hello, world!');
JSX is a syntax extension for JavaScript that allows you to write HTML-like code within JavaScript. It enhances readability and expressiveness when defining the UI of React components. JSX supports embedding JavaScript expressions, using attributes, rendering children, handling conditionals, and working with lists. It is compiled into JavaScript by tools like Babel, making it an integral part of modern React development.
@aCodeTutorials All Rights Reserved
privacy policy | about