Install create-react-app and set up your first React project:
npx create-react-app my-first-react-app
cd my-first-react-app
npm start
Real-life Example: Creating a simple app setup to work like a workspace or kitchen for building your app.
React components are reusable pieces of UI.
Code Example:
function Welcome() {
return <h1>Hello, World!</h1>;
}
export default Welcome;
Real-life Example: Components are like building blocks in LEGO, small reusable parts that come together to form a structure.
JSX is a mix of HTML and JavaScript:
const name = "John";
const element = <h1>Hello, {name}!</h1>;
Real-life Example: Like writing a recipe card where you mix ingredients (HTML) and instructions (JavaScript) in one place.
Props are arguments passed into components.
Code Example:
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
function App() {
return <Greeting name="Alice" />;
}
export default App;
Real-life Example: Props are like ingredients being passed to different stations in a kitchen.
State allows React components to change and re-render based on data.
Code Example using useState:
import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
export default Counter;
Real-life Example: State is like a shopping cart that changes as you add items.
Handling user interactions like button clicks.
Code Example:
function Button() {
const handleClick = () => {
alert("Button was clicked!");
};
return <button onClick={handleClick}>Click Me!</button>;
}
export default Button;
Real-life Example: A button that adds an item to a shopping cart.
Rendering components based on a condition.
Code Example:
function UserGreeting(props) {
return <h1>Welcome back!</h1>;
}
function GuestGreeting(props) {
return <h1>Please sign up.</h1>;
}
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <UserGreeting />;
}
return <GuestGreeting />;
}
function App() {
return <Greeting isLoggedIn={false} />;
}
export default App;
Real-life Example: Displaying a "Logged In" or "Guest" message based on the user’s login status.