Declarative SweetAlert in React
sweetalert-react is a wrapped sweetalert implementation with declarative React style component APIs. There is a show prop available for toggling alert component's visibility. And onConfirm, onCancel, onClose, onEscapeKey, onOutsideClick props allow you have a fine grained control over alert component events.
$ npm install sweetalert-react
import React, { Component } from 'react';
import SweetAlert from 'sweetalert-react';
// ...
render() {
return (
<div>
<button onClick={() => this.setState({ show: true })}>Alert</button>
<SweetAlert
show={this.state.show}
title="Demo"
text="SweetAlert in React"
onConfirm={() => this.setState({ show: false })}
/>
</div>
);
}You should import sweetalert.css from CDN, file, node_modules(sweetalert/dist/sweetalert.css) or wherever method to include this CSS file.
Checkout the full examples here.
- timer: You should use
setTimeoutand passshowas false. - closeOnConfirm: You should pass
showas false viaonConfirm. - closeOnCancel: You should pass
showas false viaonCancel. - allowEscapeKey: You should pass
showas false viaonEscapeKey. - allowOutsideClick: You should pass
showas false viaonOutsideClick.
All other options can be passed as props, see them in Configuare Section in sweetalert document
You can listen to history changes and set show: false when it is mounted. See the full example here.
Sure, you can achieve this with ReactDOMServer.renderToStaticMarkup:
import { renderToStaticMarkup } from 'react-dom/server';
<SweetAlert
show={this.state.show}
title="Demo"
html
text={renderToStaticMarkup(<HelloWorld />)}
onConfirm={() => this.setState({ show: false })}
/>See the full example here. Thanks @ArkadyB for discovering the approach in issue #53.
MIT © C.T. Lin