Created
February 14, 2024 07:32
-
-
Save tomasz-stefaniak/03ae5caad7893f2c34e538a25fbf709d to your computer and use it in GitHub Desktop.
A wrapper component with a render prop for showing a confirmation message before button click
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
// Usage: | |
// <WithConfirmation | |
// onClick={deletePost} | |
// confirmationMessage="Are you sure you want to delete this post?" | |
// renderButton={({ onClick }) => { | |
// return ( | |
// <button onClick={onClick}> | |
// Delete post | |
// </button> | |
// ); | |
// }} | |
// /> | |
export const WithConfirmation: React.FC<{ | |
renderButton: React.FC<{ | |
onClick: ( | |
event: React.MouseEvent<Element, MouseEvent> | React.FormEvent<Element>, | |
) => void; | |
}>; | |
onClick: React.EventHandler<React.MouseEvent | React.FormEvent>; | |
confirmationMessage?: string; | |
}> = ({ | |
onClick, | |
confirmationMessage = "Are you sure you want to proceed?", | |
renderButton, | |
}) => { | |
const handleClick = ( | |
event: React.MouseEvent<Element, MouseEvent> | React.FormEvent<Element>, | |
) => { | |
const confirmed = window.confirm(confirmationMessage); | |
if (confirmed) { | |
onClick(event); | |
} | |
}; | |
return renderButton({ onClick: handleClick }); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment