iamhosseindhv / notistack

Highly customizable notification snackbars (toasts) that can be stacked on top of each other
https://notistack.com
Other
3.93k stars 298 forks source link

Add dismiss button to all Snackbar #176

Closed iceleo-com closed 5 years ago

iceleo-com commented 5 years ago

The below script will show you how to add a dismiss button to all snackbars instead of adding one by one in this function "this.props.enqueueSnackbar(message, { action: (key) => () })"

Because your document doesn't have this example, so I leave it here if anyone needs it. If you can add the below script to your document, it would be nice :)

import React, { Component } from 'react';
import { SnackbarProvider } from 'notistack';
import CancelIcon from '@material-ui/icons/Cancel';

import Content from '../Content/Content';

class Conatiner extends Component {
    constructor(props) {
        super(props);

        this.state = {};

        this.notistackRef = React.createRef();
    }

    render() {
        return (
            <SnackbarProvider
                ref={this.notistackRef}
                action={(key) => (<CancelIcon onClick={() => { this.notistackRef.current.handleDismissSnack(key); }} />)}
            >
                <Content />
            </SnackbarProvider>
        );
    }
}

export default Conatiner;
iamhosseindhv commented 5 years ago

Thanks @iceleo-com ❤️. I have added this to the documentation under "Action for all snackbars" example.

It'll be online once I release the next major version. Please note that for consistency, handleDismissSnack has been renamed to closeSnackbar.

So you're gonna do something like:

// add action to all snackbars
const notistackRef = React.useRef(); // or React.createRef 
const onClickDismiss = key => () => { 
    notistackRef.current.closeSnackbar(key);
}

<SnackbarProvider
    ref={notistackRef}
    action={(key) => (
        <Button onClick={onClickDismiss(key)}>
            'Dismiss'
        </Button>
    )}
>
    <App />
</SnackbarProvider>