Course contentsShow
← React
Lesson 1166 of 2,39630. Composition: Inversion of ControlFree lesson

Prop Getter Basics: Returning an Object

Build a simple prop getter function that returns an object of props ready to spread onto a DOM element.

Prop Getter Basics: Returning an Object

What you'll learn: How to create a simple function that returns a pre-configured object of props ready to spread onto any component or element.

The Core Idea

A prop getter is just a function that returns an object. That's it. Instead of asking users to remember and manually pass 5 different props to make something work, you give them one function that bundles all those props together.

Think of it like a meal kit: instead of listing out "buy flour, eggs, sugar, butter, vanilla..." you hand someone a box with everything pre-measured and ready to combine.

The Basic Structure

function useToggle() {
  const [isOn, setIsOn] = useState(false);

  // This is a prop getter - it returns an object
  const getTogglerProps = () => {
    return {
      onClick: () => setIsOn(!isOn),
      'aria-pressed': isOn,
      role: 'button'
    };
  };

  return { isOn, getTogglerProps };
}

Using the Prop Getter

Instead of passing individual props, users spread the result:

function MyComponent() {
  const { isOn, getTogglerProps } = useToggle();

  return (
    <div>
      <button {...getTogglerProps()}>
        {isOn ? 'ON' : 'OFF'}
      </button>
    </div>
  );
}

The getTogglerProps() call returns { onClick: ..., 'aria-pressed': ..., role: ... }, and spreading it applies all those props at once.

Why Return an Object?

Objects are perfect for the spread operator. You get all the necessary props in one go, with proper names intact. The user doesn't need to know what props are needed—just that they should spread the result.

Key Takeaway: A prop getter is simply a function that returns an object of props, designed to be spread onto an element—bundling complexity into a single, convenient call.