React Bootstrap SweetAlert in React js not working

3.2k views Asked by At

I am trying to create a logout button with sweetalert. I created a logout function, and it worked perfectly without sweetalert. But when I add the sweetalert button it stops working.

Here is my code. please help me...

import React, {Component } from 'react';
import SweetAlert from 'react-bootstrap-sweetalert';

class Hero extends Component {

    constructor(props) {
        super(props);

        this.state = {
            alert: null
        };
    }  

    showAlert = () => (
            this.setState = ({
                alert: (
                    <SweetAlert
                    title="Here's a message!"
                    onConfirm={this.props.handleLogout}
                    onCancel={this.onCancel}
                    showCancel={true}
                    focusCancelBtn={true}
                    />
                )
            })
            
        );

    render(){
        return (
            <section className = "hero">
                <nav>
                    <h2>Book Exchange</h2>
                    <button onClick = {() => this.showAlert()}>Logout</button>
                </nav>
            </section>
        );
    }
};
export default Hero;

My handleLogout function is below and it worked perfectly without sweetalert. I am using firebase for auth.

const handleLogout = () => {
  fire.auth().signOut()
};
1

There are 1 answers

0
Heri Hehe Setiawan On BEST ANSWER

Note that instead of assigning setState with the new states, you should execute it as a function.

You can then, try rendering the alert conditionally, as follows:

import React, {Component } from 'react';
import SweetAlert from 'react-bootstrap-sweetalert';

class Hero extends Component {

    constructor(props) {
        super(props);

        this.state = {
            alert: false,
        };
    }  

    showAlert = () => {
      this.setState({
        alert: true,
      })
    };

    render(){
        return (
          <>
            <section className = "hero">
                <nav>
                    <h2>Book Exchange</h2>
                    <button onClick = {this.showAlert}>Logout</button>
                </nav>
            </section>
            { 
                this.state.alert && <SweetAlert
                    title="Here's a message!"
                    onConfirm={this.props.handleLogout}
                    onCancel={this.onCancel}
                    showCancel={true}
                    focusCancelBtn={true}
                    />
             }
            </>
        );
    }
};
export default Hero;