Neural Sync Active
React Introduction — Components, JSX, Props, State
Registry Synced
React Introduction — Components, JSX, Props, State
849 words
4 min read
Reading compass
Now · 🎯 Learning Objectives
React Introduction — Components, JSX, Props, State
🎯 Learning Objectives
- Create functional React components
- Use JSX to describe UI
- Pass data with props
- Manage component state with useState
- Handle events in React
- Build component trees
1. What is React?
React is a JavaScript library for building user interfaces using components. Instead of writing separate HTML files, React lets you build reusable UI pieces that manage their own state.
Key ideas:
- Components: Encapsulated UI pieces (like LEGO blocks)
- Declarative: Describe what you want, not how to do it
- React updates: When state changes, React efficiently updates the DOM
2. JSX — JavaScript XML
JSX looks like HTML but is actually JavaScript:
jsxfunction Greeting() { const name = "Alice"; return ( <div className="greeting"> <h1>Hello, {name}!</h1> <p>Welcome to React</p> </div> ); }
JSX rules:
- Use
classNameinstead ofclass(sinceclassis a JS keyword) - Use
{ }for JavaScript expressions - Must have a single root element (or use
<></>fragment) - Self-closing tags:
<img />,<br />
jsxfunction Expressions() { const user = { name: "Bob", age: 30 }; const items = ["Apple", "Banana", "Cherry"]; return ( <> <h1>{user.name} is {user.age}</h1> <ul> {items.map((item, i) => ( <li key={i}>{item}</li> ))} </ul> <button onClick={() => alert("Clicked!")}> Click me </button> </> ); }
3. Components and Props
Props (short for properties) are read-only inputs to a component:
jsx// Child component function UserCard(props) { return ( <div className="card"> <h2>{props.name}</h2> <p>Age: {props.age}</p> <p>City: {props.city}</p> </div> ); } // Parent component function App() { return ( <div> <UserCard name="Alice" age={25} city="Chennai" /> <UserCard name="Bob" age={30} city="Mumbai" /> </div> ); }
Destructuring props (recommended):
jsxfunction UserCard({ name, age, city }) { return ( <div> <h2>{name}</h2> <p>{age} years old from {city}</p> </div> ); }
4. State with useState
State is mutable data that belongs to a component. When state changes, the component re-renders.
jsxfunction Counter() { const [count, setCount] = React.useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>+</button> <button onClick={() => setCount(count - 1)}>-</button> <button onClick={() => setCount(0)}>Reset</button> </div> ); }
Rules of hooks:
- Call hooks only at the top level (not in loops, conditions, nested functions)
- Call hooks only from React function components or custom hooks
5. Event Handling
jsxfunction Form() { const [name, setName] = React.useState(''); const [submitted, setSubmitted] = React.useState(false); function handleSubmit(e) { e.preventDefault(); // Prevent page reload setSubmitted(true); } if (submitted) { return <h2>Thank you, {name}!</h2>; } return ( <form onSubmit={handleSubmit}> <input type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder="Enter your name" /> <button type="submit">Submit</button> </form> ); }
6. Component Tree
pseudoApp ├── Header │ ├── Logo │ └── Navigation │ └── NavLink (×3) ├── Main │ ├── Sidebar │ └── Content │ └── Article (×3) └── Footer
Data flows down the tree via props. Events flow up via callbacks.
7. Practice Questions
Q1: What is JSX and why is it used?Answer: JSX is a syntax extension that looks like HTML but compiles to JavaScript function calls. It allows writing UI structure in a declarative, HTML-like way within JavaScript. React converts JSX toReact.createElement()calls. Q2: What's the difference between props and state?Answer: Props are read-only inputs passed from parent to child. State is internal mutable data owned by the component. Changing props requires parent action; changing state triggers re-render of the component. Q3: Why useclassNameinstead ofclassin JSX?Answer:classis a reserved JavaScript keyword. JSX is closer to JavaScript than HTML, so it usesclassName(from the DOM API) instead. Babel/TypeScript compile it toclassNamein the resulting DOM. Q4: What doesuseStatereturn?Answer: An array with two elements: the current state value and a setter function. Using array destructuring:const [state, setState] = useState(initialValue). Q5: How do you conditionally render in React?Answer: Use ternary:{isLoggedIn ? <Dashboard /> : <Login />}. Short-circuit:{isAdmin && <AdminPanel />}. Or if/else in a function. Q6: Why do we needkeywhen rendering lists?Answer: Keys help React identify which items changed, were added, or removed. Use stable IDs (from data) rather than array indices when possible. Wrong keys cause rendering bugs and performance issues. Q7: What is the "single root element" rule in JSX?Answer: A component must return a single root element. To avoid extra divs, use<>...</>(React Fragment), which doesn't add a DOM node. Q8: Create a component that takestitleandbodyprops and renders them.jsxfunction Note({ title, body }) { return ( <div className="note"> <h2>{title}</h2> <p>{body}</p> </div> ); }
📐 Key Concepts
| Concept | Syntax | Purpose |
|---|---|---|
| Component | function Comp() { } | Reusable UI piece |
| JSX | text | Declarative UI in JS |
| Props | function Comp({prop}) | Read-only inputs |
| State | useState(init) | Mutable data, triggers re-render |
| Event | onClick={handler} | User interaction |
| Key | key={item.id} | List identity for React |