Display confirmation buttons on clicking a button

Working in any application deveploment project, there are many situations we want to put a safety gate before a user can execute some hard to go back changes to the application data. For example, like deleting data permanently, or executing a very high critical process.
Doing a confirmation wall in React to button is kind of easy, but if we have to do it many times it becomes tedious. And sometimes we keep repeating the similar code over and over again in many places. Hence, we got a class that is quite bulky for repeating the same codes on many different buttons.
When all I want is for simple confirmation yes or no before executing any instructions, I think a simple confirmation button will do it. I come up with what I called ConfirmButton component. Here is the code in the codepen, https://codepen.io/mjunaidi/pen/mqPGdw.
Or here is the code;
class ConfirmButton extends React.Component{
constructor(props){
super(props)
this.state = {
label: props.label||'Unlabelled',
question: props.question||'Confirm?',
confirmed: false,
className: props.className?'btn '+props.className:'btn'
}
}
render() {
return (
<div>
{
this.state.confirmed!==true&&
<button
type="button"
className={this.state.className}
onClick={()=>{this.setState({confirmed:true})}}>
{this.state.label}
</button>
||
(
<div>
<span className="mr-3">{this.state.question}</span>
<button
name={this.props.name}
type="button"
className="btn btn-success mr-3"
onClick={(event)=>{
this.props.onClick(event)
this.setState({confirmed:false})
}}>
Yes
</button>
<button
type="button"
className="btn btn-danger"
onClick={()=>{this.setState({confirmed:false})}}>
No
</button>
</div>
)
}
</div>
)
}
}
To use it, we can go simply by;
<ConfirmButton label="Delete" onClick={this.handleClick}/>
Where this.handleClick
is defined in the parent component that is calling the ConfirmButton component. The ConfirmButton component will simply execute the action on confirm button Yes
is clicked.
In case we want to more style or we want to actually tie the component with any function in the parent app we can actually give the confirmation button a name;
<ConfirmButton
name="delete"
label="Delete"
question="Are you sure?"
className="btn-warning"
onClick={this.handleClick}
/>
As we can see here, we can define the question to ask with question
attribute. And give furher CSS class to use for the button with className
attribute.
Thanks for reading!