React Holiday

Trust the Prop-cess

The estute reader is worrying about props right now. Prop-handling is a crucial part of component design that I’ve conveniently left it out.

For simple components like our Greeting, it’s common to take the rest of the props and apply them to the returned element.

function Greeting({ as: As = React.Fragment, name, ...props }) {
  return <As {...props}>Hello {name}</As>;
}

This ensures native element attributes like className, id, and aria-label get “forwarded” to the returned element.

But what happens when we provide className to our default Fragment and there is no element? I’m glad you asked…

Invalid prop supplied to React.Fragment

React has terrific errors. This one teaches us that Fragment — when used as our root — can only take key and children as props.

Take it home

There are two ways to resolve this warning. I’m curious which one you reach for. Fork this week’s CodeSandbox and reply with your solution. Or join our discussion in Discord to see how others solved it!