Day - 3
Day-3 of Learning React.js
π Step-by-Step Explanation
1. Imports
import React, { useState } from "react";
Reactβ allows you to write JSX (HTML-like code inside JavaScript).useStateβ a React hook that lets you store and update data inside a function component.
2. Function Component
function App() {
Appis a function component.Components are like building blocks of your UI.
This one is the main component of your app.
3. useState Hook
const [theme, setTheme] = useState("dark");
themeβ state variable that stores the current theme ("dark"by default).setThemeβ function used to change the theme.useState("dark")β initializes the state with"dark".
π Think of it like:
theme= box holding the current theme.setTheme= tool to replace whatβs inside the box.
4. Toggle Function
const toggleTheme = () => {
const newTheme = (theme === "dark") ? "light" : "dark";
setTheme(newTheme);
};
This function switches between
"dark"and"light".(condition ? true : false)β called ternary operator.If
theme === "dark", thennewTheme = "light".Otherwise,
newTheme = "dark".
setTheme(newTheme)β updates the state with the new theme.
5. JSX (UI Part)
return (
<div className={"main " + theme}>
<button onClick={toggleTheme}>
{theme}
</button>
<p>Lorem ipsum...</p>
</div>
);
<div className={"main " + theme}>Adds a CSS class dynamically.
Example: if
theme = "dark", class becomes"main dark".If
theme = "light", class becomes"main light".
<button onClick={toggleTheme}>Button that runs
toggleThemewhen clicked.Inside button β
{theme}shows current theme text (darkorlight).
<p>...</p>β just a sample paragraph.
6. Export
export default App;
export defaultβ sends out the whole component so other files can use it.If you used just
export, you could export multiple things individually.
7. Your Comments
// export default ka matalb entire file
// export ka matalb indivusual
// we wrap the js code in {} curly brases
β Correct!
export defaultβ one main thing from file.exportβ many individual things.{}curly braces β used in JSX to run JavaScript code inside HTML-like structure.
π Key Notes in Simple Words
React β library for building UI with components.
Component β function that returns UI.
useState β lets you store and change data.
Ternary Operator β short way to write
if...else.Dynamic className β changes CSS class based on state.
Controlled UI β React decides what to show based on state.
export default β export one main thing.
{} curly braces β run JavaScript inside JSX.
