01 React Basics
JSX (JavaScript XML)¶
- JSX allows you to write HTML-like code in JavaScript files. It makes React code more readable and intuitive.
- Translated to JavaScript using tools like Babel.
Example: JSX¶
const element = <h1>Hello, world!</h1>;
ReactDOM.createRoot(document.getElementById('root')).render(element);
JSX Rules¶
-
Return a single parent element:
-
JavaScript expressions inside
{}: -
Use camelCase for attributes:
React Components¶
-
Functional Components:
- A simple JavaScript function that returns JSX.
- Can use React Hooks to manage state and lifecycle.
-
Class Components:
- A JavaScript class that extends
React.Componentand has arender()method.
- A JavaScript class that extends
Props (Properties)¶
Props are used to pass data from a parent component to a child component. They are immutable (cannot be changed by the child).
Example: Using Props¶
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
// Usage:
<Welcome name="Alice" />
State¶
State is a way to manage dynamic data within a component. When the state changes, the component re-renders.
Handling Events¶
React events are similar to DOM events, but they use camelCase syntax and a function reference.