May be you can use higher order component here.
SnackbarWrapper.js
import React from 'react';
import PropTypes from 'prop-types';
const SnackbarWrapper = (Component) => {
class Decorated extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
active: props.active
};
this.handleSnackbarClick = this.handleSnackbarClick.bind(this);
this.handleSnackbarTimeout = this.handleSnackbarTimeout.bind(this);
}
componentWillReceiveProps(nextProps) {
// snackbar activated from outside
if (this.props.active !== nextProps.active) {
this.setState({ active: true });
}
}
handleSnackbarClick(event, instance) {
// snackbar dismissed from inside
this.setState({ active: false });
// handle the dispatch in callback function
this.props.cb();
}
handleSnackbarTimeout(event, instance) {
// snackbar dismissed from inside
this.setState({ active: false });
// handle the dispatch in callback function
this.props.cb();
}
render() {
const { action, label, type, timeout } = this.props;
return (
<Component
action={action}
label={label}
type={type}
timeout={timeout}
active={this.state.active}
onClick={this.handleSnackbarClick}
onTimeout={this.handleSnackbarTimeout}
/>
);
}
}
Decorated.propTypes = {
action: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
type: PropTypes.string.isRequired,
timeout: PropTypes.number.isRequired,
cb: PropTypes.func.isRequired,
active: PropTypes.bool.isRequired
};
return Decorated;
};
export default SnackbarWrapper;
in your component
import SnackbarWrapper from './SnackBarWrapper';
const RTSnackbar = SnackbarWrapper(Snackbar);
...
<RTSnackbar
action="Dismiss"
label="Snackbar action cancel"
type="cancel"
timeout={2000}
cb={this.actionCb}
active={this.state.active}
/>