I'm trying to build a reusable Confirmation component that renders a button and when clicked, it should open a Material UI Dialog. The button component gets passed in as a prop for the Confirmation component
<Confirmation component={() => <MUIButton>Click me</MUIButton>} />
The parent component looks like this
const Confirmation = ({ component: Component }) => {
const handleClick = () => {
...logic to open the dialog...
}
return (
<>
<Component onClick={handleClick} <-- how to trigger this? />
<Dialog />
</>
)
}
Now how would I get this to work without having to specify the onClick in the passed button component itself? For this situation one can assume the component passed as a prop is always some kind of a button.
<Confirmation
component={() => (
<MUIButton
onClick={...logic} <-- don't want to have to specify this
>
Click me
</MUIButton>
)
/>
OR am I approaching this from a wrong perspective? Should this be solved by passing the button as a child instead? As in
<Confirmation>
<MUIButton> Click me </MUIButton>
</Confirmation>
and how would the implementation be in this situation?
Thank you in advance!
Ended up solving this by creating a higher order component as suggested by John
const withConfirmation = (WrappedComponent) => {
return (props) => {
return (
<>
<WrappedComponent
// Overrides the possible onClick logic passed as a prop
onClick={ ...dialog opening logic }
{...props}
/>
<Dialog>
...
</Dialog>
</>
);
};
};
const Confirmation = withConfirmation(MuiButton)
<Confirmation>Clicking me opens a dialog</Confirmation>