A shortcut would be Yuri Piskunov's answer, i.e.
handleClick() {
alert("hi");
this.setState({ showing: false });
}
I would take a longer approach by using a library called react-alert
This would also allow you to style your Alert box and give you more control
Github: https://github.com/schiehll/react-alert
demo: https://codesandbox.io/s/vibrant-hawking-7ywz9?file=/src/Foo.js:196-271
install react-alert and react-alert-template-mui
yarn add react-alert
yarn add react-alert-template-mui
in App.js
import React from "react";
import "./styles.css";
import Foo from "./Foo";
import { Provider } from "react-alert";
import AlertMUITemplate from "react-alert-template-mui";
export default function App() {
return (
<div className="App">
<Provider template={AlertMUITemplate}>
<Foo />
</Provider>
</div>
);
}
and Foo.js
import React from "react";
import "./styles.css";
import { withAlert } from "react-alert";
class Foo extends React.Component {
state = {
showing: false,
alert: this.props.alert
};
handleClick() {
this.state.alert.show("Oh look, an alert!", {
onClose: () => {
this.setState({ showing: false });
} // callback that will be executed after this alert is removed
});
}
render() {
const { showing } = this.state;
return (
<div>
<button onClick={() => this.setState({ showing: !showing })}>
toggle
</button>
{showing ? (
<div className="box">
<div
className="style1"
onClick={() => this.handleClick(this.props)}
>
Action1
</div>
</div>
) : null}
</div>
);
}
}
export default withAlert()(Foo);