react-bootstrap-sweetalert
SweetAlert for React/Bootstrap
An awesome replacement for JavaScript's alert.
Support
If you think I've done a good job, consider showing your support by buying me a beer. Cheers! :beers:
Demo & Examples
See the demo with examples of common use cases and a live editor.
:alien: TAKE ME TO YOUR DEMO :alien:
Getting Started
Installation
$ npm i react-bootstrap-sweetalert
or
$ yarn add react-bootstrap-sweetalert
Import
const SweetAlert = require('react-bootstrap-sweetalert');
or
import SweetAlert from 'react-bootstrap-sweetalert';
Recommended Usage
It is recommended that you keep an alert in your state, and remove it when the onConfirm or onCancel callbacks are invoked.
You can have stackable alerts by keeping an array of alerts in your data store, and always providing the first alert in the array as the visible alert. When an alert is closed, remove it from the store.
See examples/redux for a working example of how to implement stackable alerts with a Redux store.
Tip: Receiving an input value
If you're using input type, the value of the input will be sent to the onConfirm callback as the first argument.
onConfirm={(response) => this.onRecieveInput(response)}
Custom Forms / Using Render Props
If you want to build an alert that re-renders based on external state changes, or simply want to build a custom form, then you will find the render props pattern to be your best option.
- For re-rendering based on external state changes, use props.dependencies
- See the
SweetAlertRenderPropsinterface in types.ts for some information on the available render props.
<SweetAlert
title={"Uses render props"}
onConfirm={this.onConfirm}
onCancel={this.onCancel}
dependencies={[this.state.firstName, this.state.lastName]}
>
{(renderProps: SweetAlertRenderProps) => (
<form>
Your name is: {this.state.firstName} {this.state.lastName}
<hr/>
<input
type={'text'}
ref={renderProps.setAutoFocusInputRef}
className="form-control"
value={this.state.firstName}
onKeyDown={renderProps.onEnterKeyDownConfirm}
onChange={(e) => this.setState({ firstName: e.target.value })}
placeholder={'First name'}
/>
<br />
<input
type={'text'}
className="form-control"
value={this.state.lastName}
onKeyDown={renderProps.onEnterKeyDownConfirm}
onChange={(e) => this.setState({ lastName: e.target.value })}
placeholder={'Last name'}
/>
<hr/>
</form>
)}
</SweetAlert>
Changes in version 5.2
- Added
props.dependenciesthat re-renders the alert whenever the provided Array ofdependenciesvalue changes. - Added new supported value of
'controlled'forprops.type. Ifprops.type === 'controlled'thenprops.onConfirmwill returnprops.dependencies. - Added support for using a function as your alert content/children, aka render props.
For more see CHANGE_LOG.md
Props
- title (required)
- type
- onConfirm (required)
- onCancel
- customIcon
- allowEscape
- closeOnClickOutside
- hideOverlay
- timeout
- show
- dependencies
Buttons
- btnSize
- confirmBtnText
- confirmBtnBsStyle
- confirmBtnCssClass
- confirmBtnStyle
- cancelBtnText
- cancelBtnBsStyle
- cancelBtnCssClass
- cancelBtnStyle
- showCloseButton
- reverseButtons
- customButtons
- focusConfirmBtn
- focusCancelBtn
- closeBtnStyle
- showConfirm
- showCancel
- disabled
Input
Hooks
Styling
Animations
props.title
The text to display for the title. JSX/ReactNode allowed.
- Type:
ReactNode|string -
Default:
undefinedprops.onConfirmInvoked when user clicks confirm button. Also invoked if user hits ENTER key.
- Type:
(response?: any) => any -
Default:
undefinedprops.onCancelInvoked when user clicks cancel button. Also invoked if allowEscape is true and user hits ESCAPE key.
- Type:
() => any -
Default:
undefinedprops.typeThe type of alert to display.
- Type:
'default'|'info'|'success'|'warning'|'danger'|'error'|'input'|'custom'|'controlled' - Default:
'default'
NOTE
- If
props.type === 'controlled'thenprops.onConfirmwill receiveprops.dependenciesas its first argument.If
props.type === 'input'thenprops.onConfirmwill receiveprops.dependenciesas its first argument.
props.btnSizeThe type of alert to display.
- Type:
'lg'|'sm'|'xs'- Default:
'lg'Allowed values:
'lg','sm','xs'
props.confirmBtnTextContent of confirm button, or JSX/ReactNode.
- Type:
ReactNode|stringDefault:
'OK'
props.confirmBtnBsStyleBootstrap style of confirm button.
- Type:
'default'|'primary'|'link'|'info'|'success'|'warning'|'danger'|'secondary'|'outline-{variant}'Default:
'primary'
props.confirmBtnCssClassCSS class added to confirm button.
- Type:
stringDefault:
''
props.confirmBtnStyleInline style added to confirm button.
- Type:
CSSPropertiesDefault:
{}
props.cancelBtnTextContent of cancel button, or JSX/ReactNode.
- Type:
ReactNode|stringDefault:
'Cancel'
props.cancelBtnBsStyleText of cancel button, or JSX/ReactNode.
- Type:
string- Default:
'link'Recommended values:
'default'|'primary'|'link'|'info'|'success'|'warning'|'danger'|'secondary'|'outline-{variant}'
props.cancelBtnCssClassCSS class added to cancel button.
- Type:
stringDefault:
''
props.cancelBtnStyleInline style added to cancel button.
- Type:
CSSPropertiesDefault:
{}
props.showCloseButtonIf set to true, then an X close button will be shown in the top right of the alert.
NOTE: You must also implement
props.onCancelin order for this props to work. This is because visibility of the component is controlled externally through eitherprops.showor by removing the<SweetAlert />in your render method.
- Type:
boolean -
Default:
falseprops.reverseButtonsReverses the order of the Confirm and Cancel buttons. Default positioning is [Cancel] [Confirm]
- Type:
boolean -
Default:
falseprops.customButtonsCustom buttons to use in place of the default Confirm and Cancel buttons. Can render any JSX/ReactNodes here.
- Type:
ReactNode -
Default:
undefinedprops.customIconEither a string url for an image to use as the icon, or JSX/ReactNode.
- Type:
ReactNode|string -
Default:
undefinedprops.placeholderIf
props.typeis'input', this is the placeholder for the input field. - Type:
string -
Default:
undefinedprops.showIf false, the alert will not be rendered. Warning: Using this option should be a last resort, and is somewhat of an anti-pattern for this library. The recommended way to control visibility is to only render a
<SweetAlert/>element when you want one to be displayed, and remove it when theonConfirmoronCancelmethods are called. - Type:
boolean -
Default:
trueprops.dependenciesIf you have external state that should trigger your alert to re-render it's content, you can provide an
Arrayofdependencies. Whenever the dependencies are changed, using===comparision, the content of the alert will be re-rendered. - Type:
any[] - Default:
true
Example
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
<SweetAlert dependencies={[firstName, lastName]}>
<div>
<h4>Hello {{firstName}} {{lastName}}</h4>
<input value={firstName} onChange={(e) => setFirstName(e.target.value)} />
<input value={lastName} onChange={(e) => setLastName(e.target.value)} />
</div>
</SweetAlert>
props.focusConfirmBtn
If true the Confirm button will receive focus automatically. NOTE: Does not apply when props.type is 'input'
- Type:
boolean -
Default:
trueprops.focusCancelBtnIf true the Cancel button will receive focus automatically. NOTE: Does not apply when
props.typeis'input' - Type:
boolean -
Default:
falseprops.requiredIf
props.typeis'input', this prop controls whether the input field is required to have a value. - Type:
boolean -
Default:
trueprops.validationMsgIf
props.typeis'input'andprops.requiredistrue, this is the message to display when the user clicks confirm without entering a value. - Type:
string -
Default:
'Please enter a response!'props.validationRegexIf
props.typeis'input'andprops.requiredistrue, this Regex is used to validate input value. - Type:
RegExp -
Default:
/^.+$/props.defaultValueIf
props.typeis'input', this is the default value for the input field. - Type:
number|string -
Default:
undefinedprops.inputTypeIf
props.typeis'input', this is the default value for the input field. - Type:
string - Default:
'text' -
Recommended values:
'text'|'password'|'number'|'textarea'props.styleStyle overrides applied to the sweetalert wrapper.
- Type:
CSSProperties -
Default:
{}props.closeBtnStyleStyle overrides applied to the X close button.
- Type:
CSSProperties -
Default:
{}props.customClassCustom CSS class applied to the sweetalert wrapper.
- Type:
string -
Default:
''props.showConfirmIf
true, the Confirm button will show. - Type:
boolean -
Default:
trueprops.showCancelIf
true, the Cancel button will show. - Type:
boolean -
Default:
falseprops.allowEscapeIf
true, theonCancelfunction will be invoked when the user hits theESCAPEkey. - Type:
boolean -
Default:
trueprops.closeOnClickOutsideIf
true, theonCancelfunction will be invoked when clicking outside the modal. - Type:
boolean -
Default:
trueprops.hideOverlayIf
true, then the modal overlay will not be rendered. - Type:
boolean -
Default:
falseprops.disabledIf
true, then the Confirm button will be disabled. (NOTE: This does not effect theprops.allowEscapebehavior.) If you set disabled totruebut do not provide anonCancelfunction, then thedisabledproperty will not be honored. - Type:
boolean -
Default:
falseprops.beforeMountHook which is invoked at the end of the component
constructorfunction. - Type:
() => any -
Default:
() => {}props.afterMountHook which is invoked at the end of the
componentDidMountmethod. - Type:
() => any -
Default:
() => {}props.afterUpdateHook which is invoked at the end of the
componentDidUpdatemethod. - Type:
() => any -
Default:
() => {}props.beforeUnmountHook which is invoked at the end of the
componentWillUnmountmethod. - Type:
() => any -
Default:
() => {}props.timeoutIf defined, and greater than
0,props.onConfirmwill be invoked to close the alert automatically after the specified number of milliseconds. - Type:
number -
Default:
0props.openAnimProvide custom show animation or false to have no animation. To specify a custom animation, provide the name of your css animation and duration of the animation in milliseconds.
- Type:
boolean|SweetAlertAnimationProps -
Default:
{ name: 'showSweetAlert', duration: 300 }props.closeAnimProvide custom hide animation or false to have no animation. To specify a custom animation, provide the name of your css animation and duration of the animation in milliseconds. For a simple hide animation you can use
{ name: 'hideSweetAlert', duration: 100 } - Type:
boolean|SweetAlertAnimationProps - Default:
false
Related projects
- SweetAlert
- SweetAlert for Android
- SweetAlert for Bootstrap
- SweetAlert for AngularJS
- SweetAlert for RubyOnRails
Development
$ yarn demo && open http://localhost:3000
Openbase Dashboard

