SyntaxStudy
Sign Up
React Passing and Receiving Props
React Beginner 1 min read

Passing and Receiving Props

Props (short for properties) are the mechanism by which a parent component passes data and callbacks down to child components. In JSX, props look like HTML attributes: you write them on the component tag and React collects them into a plain object that is passed as the first argument to the component function. Props can carry any JavaScript value — strings, numbers, booleans, arrays, objects, functions, and even other JSX elements. Boolean props with a `true` value can be written in shorthand: `` is identical to ``. Expressions — including variables, computed values, and function references — are passed using curly braces. Spreading an existing props object with `{...props}` is a handy shortcut when forwarding props to a child or extending a component. Props are strictly read-only. A component must never modify the object it receives because that would break React's unidirectional data flow and make the application unpredictable. If a child needs to communicate back to its parent — for instance to report a button click — the parent passes a callback function as a prop, and the child calls it. This "props down, events up" pattern is the foundation of React data management.
Example
// Parent passes props; child reads them (read-only)
function ProductCard({ name, price, inStock, onAddToCart }) {
  return (
    <div style={{ border: '1px solid #ddd', padding: 16, borderRadius: 8 }}>
      <h3>{name}</h3>
      <p>Price: ${price.toFixed(2)}</p>
      <p>
        Availability:{' '}
        <strong style={{ color: inStock ? 'green' : 'red' }}>
          {inStock ? 'In Stock' : 'Out of Stock'}
        </strong>
      </p>
      {/* Callback prop — child calls it, parent handles it */}
      <button disabled={!inStock} onClick={() => onAddToCart(name)}>
        Add to Cart
      </button>
    </div>
  );
}

function Shop() {
  const products = [
    { id: 1, name: 'Keyboard', price: 89.99, inStock: true },
    { id: 2, name: 'Monitor',  price: 349.00, inStock: false },
  ];

  const handleAdd = (name) => alert(`${name} added to cart`);

  return (
    <div>
      {products.map(p => (
        <ProductCard
          key={p.id}
          name={p.name}
          price={p.price}
          inStock={p.inStock}
          onAddToCart={handleAdd}
        />
      ))}
    </div>
  );
}

export default Shop;