Kevin De Baerdemaeker

Using React Context to pass props to Dynamic Children

Modified 2022-09-23

If you want to keep the flexibility of letting the user decide what they render inside for example a <Dialog />, but keep the title of it accessible when the user decides to add a title, passing the titleProps through context is a great idea.

export function Dialog() {
    return (
        <DialogContext.Provider value={{ titleProps }}>{children}</DialogContext.Provider>
    )
}
export function DialogTitle(props) {
  const { titleProps } = React.useContext(DialogContext)

  return (
    <Typography {...props} {...titleProps} variant="h3">
      {props.children}
    </Typography>
  )
}

So now on the consumer side, they can either choose to include the title in the content of the dialog or not. But if they do, it's certain the props are properly set, and they can display the title on the bottom of the dialog if they want to.

export function SomeSpecificDialog(props) {
  return (
    <Dialog>
      <DialogTitle>Annie, you okay?</DialogTitle>
    </Dialog>
  )
}