JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code in your JavaScript files. It simplifies creating and rendering React components.
Example JSX Code:
const element = <h1>Hello, JSX!</h1>;
Rules of JSX:
Single Root Element: Wrap all JSX in a single root element.
return (
<div>
<h1>Hello</h1>
<p>Welcome to React!</p>
</div>
);
JavaScript Expressions: Embed JavaScript using curly braces {}.
const name = 'React Developer';
return <h1>Welcome, {name}!</h1>;
Self-Closing Tags: Close tags for elements without children.
<img src="logo.png" alt="React Logo" />
CSS Class Names: Use className instead of class.
<div className="container">Hello</div>
Conditionals in JSX: Use ternary operators for conditional rendering.
Props (Properties): Props are used to pass data from one component to another, making components reusable and dynamic. Props are read-only and cannot be modified by the receiving component.
Example Using Props:
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
// Using the component
<Welcome name="John" />
State: State is a built-in object that holds data or information about a component. Unlike props, state is mutable and managed within the component itself.
Using State in Functional Components (with Hooks):