Skip to content

Instantly share code, notes, and snippets.

@tomasz-stefaniak
Created February 14, 2024 07:32
Show Gist options
  • Save tomasz-stefaniak/03ae5caad7893f2c34e538a25fbf709d to your computer and use it in GitHub Desktop.
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
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