Quiz 2
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:
jsx
function Greeting() {
    const name = "Alice";
    return (
        <div className="greeting">
            <h1>Hello, {name}!</h1>
            <p>Welcome to React</p>
        </div>
    );
}
JSX rules:
  • Use className instead of class (since class is a JS keyword)
  • Use { } for JavaScript expressions
  • Must have a single root element (or use <></> fragment)
  • Self-closing tags: <img />, <br />
jsx
function 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):
jsx
function 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.
jsx
function 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

jsx
function 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

pseudo
App
├── 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 to React.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 use className instead of class in JSX?
Answer: class is a reserved JavaScript keyword. JSX is closer to JavaScript than HTML, so it uses className (from the DOM API) instead. Babel/TypeScript compile it to className in the resulting DOM. Q4: What does useState return?
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 need key when 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 takes title and body props and renders them.
jsx
function Note({ title, body }) {
    return (
        <div className="note">
            <h2>{title}</h2>
            <p>{body}</p>
        </div>
    );
}

📐 Key Concepts

ConceptSyntaxPurpose
Componentfunction Comp() { }Reusable UI piece
JSXtextDeclarative UI in JS
Propsfunction Comp({prop})Read-only inputs
StateuseState(init)Mutable data, triggers re-render
EventonClick={handler}User interaction
Keykey={item.id}List identity for React

🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.