UNPKG

2.36 kBJavaScriptView Raw
1import React from 'react';
2import PropTypes from 'prop-types';
3import classNames from 'classnames';
4import { mapToCssModules, tagPropType } from './utils';
5import Fade from './Fade';
6
7const propTypes = {
8 /** Pass children so this component can wrap the child elements */
9 children: PropTypes.node,
10 /** Add custom class */
11 className: PropTypes.string,
12 /** Add custom class for close button */
13 closeClassName: PropTypes.string,
14 /** Aria label for close button */
15 closeAriaLabel: PropTypes.string,
16 /** Change color of alert */
17 color: PropTypes.string,
18 /** Change existing className with a new className */
19 cssModule: PropTypes.object,
20 /** Toggle fade animation */
21 fade: PropTypes.bool,
22 innerRef: PropTypes.oneOfType([
23 PropTypes.object,
24 PropTypes.string,
25 PropTypes.func,
26 ]),
27 /** Control visibility state of Alert */
28 isOpen: PropTypes.bool,
29 /** Set a custom element for this component */
30 tag: tagPropType,
31 /** Function to toggle visibility */
32 toggle: PropTypes.func,
33 /** Props to be passed to `Fade` to modify transition */
34 transition: PropTypes.shape(Fade.propTypes),
35};
36
37function Alert(props) {
38 const {
39 className,
40 closeClassName,
41 closeAriaLabel = 'Close',
42 cssModule,
43 tag: Tag = 'div',
44 color = 'success',
45 isOpen = true,
46 toggle,
47 children,
48 transition = {
49 ...Fade.defaultProps,
50 unmountOnExit: true,
51 },
52 fade = true,
53 innerRef,
54 ...attributes
55 } = props;
56
57 const classes = mapToCssModules(
58 classNames(className, 'alert', `alert-${color}`, {
59 'alert-dismissible': toggle,
60 }),
61 cssModule,
62 );
63
64 const closeClasses = mapToCssModules(
65 classNames('btn-close', closeClassName),
66 cssModule,
67 );
68
69 const alertTransition = {
70 ...Fade.defaultProps,
71 ...transition,
72 baseClass: fade ? transition.baseClass : '',
73 timeout: fade ? transition.timeout : 0,
74 };
75
76 return (
77 <Fade
78 {...attributes}
79 {...alertTransition}
80 tag={Tag}
81 className={classes}
82 in={isOpen}
83 role="alert"
84 innerRef={innerRef}
85 >
86 {toggle ? (
87 <button
88 type="button"
89 className={closeClasses}
90 aria-label={closeAriaLabel}
91 onClick={toggle}
92 />
93 ) : null}
94 {children}
95 </Fade>
96 );
97}
98
99Alert.propTypes = propTypes;
100
101export default Alert;