React Fundamentals

Learn React from scratch including components, JSX, props, and state basics.

beginner Frontend Frameworks 5 hours

Chapter 5: Props

Chapter 5 of 15

Chapter 5: Props

5.1 Passing Props

Props (properties) allow passing data from parent to child components. Props are read-only and flow downward.

// Parent component
function App() {
    return <Greeting name="John" age={30} />;
}

// Child component receives props
function Greeting(props) {
    return (
        <div>
            <h1>Hello, {props.name}!</h1>
            <p>Age: {props.age}</p>
        </div>
    );
}

Props Characteristics:

  • Read-only (immutable)
  • Passed from parent to child
  • Can be any JavaScript value
  • Accessible via props object

Passing Different Data Types:

// String
<Component name="John" />

// Number
<Component count={42} />

// Boolean
<Component isActive={true} />

// Object
<Component user={{ name: 'John', age: 30 }} />

// Array
<Component items={[1, 2, 3]} />

// Function
<Component onClick={handleClick} />

5.2 Props Destructuring

Destructuring props makes code cleaner and more readable.

// Without destructuring
function Greeting(props) {
    return <h1>Hello, {props.name}!</h1>;
}

// With destructuring
function Greeting({ name, age }) {
    return (
        <div>
            <h1>Hello, {name}!</h1>
            <p>Age: {age}</p>
        </div>
    );
}

// With default values
function Greeting({ name = 'Guest', age = 0 }) {
    return <h1>Hello, {name}!</h1>;
}

5.3 Children Prop

The children prop allows passing content between component tags.

function Card({ title, children }) {
    return (
        <div className="card">
            <h2>{title}</h2>
            {children}
        </div>
    );
}

// Usage
<Card title="User Info">
    <p>This is the card content</p>
    <button>Click me</button>
</Card>

5.4 Props Best Practices

Follow best practices when working with props.

  • Use descriptive prop names
  • Provide default values when appropriate
  • Validate props with PropTypes or TypeScript
  • Don't mutate props
  • Keep prop lists manageable (extract to objects if too many)