React jsx syntax
Created By: chatGPT
In React, JSX (JavaScript XML) allows you to write HTML-like syntax directly within your JavaScript code. It makes it easy to describe the UI structure and components. JSX gets compiled into JavaScript, enabling the creation of React elements that can be rendered.
const element = <h1>Hello, world!</h1>;
You can include JavaScript expressions inside curly braces
{}
within JSX. This is useful for dynamically rendering data or expressions.const name = 'John';
const greeting = <h1>Hello, {name}!</h1>;
JSX also supports components. You can create your own components and use them as custom HTML tags. Components must start with a capital letter.
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
const element = <Welcome name='Sara' />;
In JSX, you can use className instead of class for assigning CSS classes, as
class
is a reserved keyword in JavaScript.<div className='container'>
<h1>My Title</h1>
</div>;
You can create multi-line JSX by wrapping it in parentheses and ensuring that the return statement is formatted correctly. This enhances readability for longer components.
const App = () => (
<div>
<h1>Welcome to React!</h1>
<p>This is a simple application.</p>
</div>
);
You can also handle events in JSX by using camelCase syntax for event names, and passing functions as event handlers.
function handleClick() {
alert('Button clicked!');
}
const element = <button onClick={handleClick}>Click me</button>;