1

I want to use handleChange in the <Tab/> component but couldn't get it done.

const handleChange = (event, newValue) => {
setValue(newValue)
}

How can I access onChange prop on <Tab/> component?

<TabHeader value={value} onChange={handleChange}>
      <Tab label="Tab1" />
      <Tab label="Tab2" />
      <Tab label="Tab2" />
</TabHeader>

Here's my <TabHeader/> component:

function TabHeader(props) {
  const { children, value, onChange, ...other } = props

  return (
    <ul>
      {children} <--- Tab components
    </ul>
  )
}
WindCheck
  • 374
  • 1
  • 9

1 Answers1

1

Have you tried cloneElement?

function TabHeader(props) {
  const { children, onChange } = props;

  const childWithProps = Children.map(children, (child) =>
    isValidElement(child) ? cloneElement(child, { onChange }) : null
  );

  return <ul>{childWithProps}</ul>;
}

Working solution can be found here: https://codesandbox.io/s/suspicious-dawn-h56von?file=/src/App.js:514-754

Ref: How to pass props to {this.props.children}

Shyam Mittal
  • 188
  • 2
  • 9