Kavindu udara
SE Undergaduate
github-profile-image

Props in React

Posted on Dec 1, 2024

Props (short for properties) are used to pass data from a parent component to a child component. Props are read-only, meaning they cannot be modified by the child component receiving them.


Key Features of Props

  • Passed as an object to the component.
  • Immutable (cannot be changed by the component receiving them).
  • Used for dynamic data and reusability.

How to Pass Props Between Components

  1. Define props in the parent component

    function Parent() {
    const name = "John";
    return <Child name={name} />;
    }
    
  2. Access props in the child component

    function Child(props) {
    return <h1>Hello, {props.name}!</h1>;
    }
    
  3. Destructure props for cleaner syntax

    function Child({ name }) {
    return <h1>Hello, {name}!</h1>;
    }
    

Example of Props

function Button({ label, onClick }) {
    return <button onClick={onClick}>{label}</button>;
}

function App() {
    const handleClick = () => alert("Button clicked!");
    return <Button label="Click Me" onClick={handleClick} />;
}

References