简体   繁体   中英

Open and close React Material UI Snackbar component programmatically

I'm trying to programme an SPA in React/Material-UI and I'm having some issues. I've developed a modal login box that is launched from a button on a navbar. When the user presses submit I call a backend api using fetch and depending on the result of the returned status code I want to open a snackbar component with certain information or close the modal login window.

I've learnt to open snackbars by clicking on a link but how can I open one programmically? I also need to close my modal window upon success of the api call and I don't know how to achieve this either. I can also achieve this by manually clicking on a link that is bound to original button on the nav bar.

I've tried using the basic snackbar example from the docs and putting it in a separate component but it only shows how to launch those by clicking on a link that's already in the actual Snackbar functional component. I need to know how to display a snackbar programmatically from another component.

I'm pretty sure I'm missing something obvious:)

Login.js React Component

import React, {Component} from 'react'
import Button from '@material-ui/core/Button'
import TextField from '@material-ui/core/TextField'
import CustomizedSnackbars from './CustomSnackbars'

class LoginDialog extends Component {

    constructor(props) {
        super(props);
        this.state = {username: "",
                      password: ""};

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event) {
      <some code>
    }

    handleSubmit(event) {
        event.preventDefault();
        const data = {
            "username":this.state.username,
            "password":this.state.password
        }

        fetch("https://mywebsite.com/auth/login", {
            method: "POST",
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body:  JSON.stringify(data)
        })
        .then(function(response){
            if (response.status === 200) {
                console.log("good boye") 
                //---------------------------------
                // WANT TO CLOSE LOGIN DIALOG HERE;
                //---------------------------------
            } else if (response.status === 401) {
                console.log("naughty naughty")
                //---------------------------------
                // WANT TO DISPLAY SNACKBAR HERE
                //---------------------------------
            } else if (response.status === 502) {
                console.log("off it's hinges, innit")
            } else {
                console.log("sumat went bang")
            }
            return response.json();
        });
    }

    render() {
        return (
            <div className="modal-outer">
            <div className="modal-inner">
                <h3>Login</h3>
                <TextField
                />
                <br />
                <TextField
                />
                <Button variant="outlined" onClick={this.props.closePopup} color="secondary">
                    Cancel
                </Button>
                &nbsp;
                <Button variant="outlined" onClick={(event) => this.handleSubmit(event)} color="primary">
                    Login
                </Button>
            </div>
            </div>
        );
  }
}

export default LoginDialog

Can I call/make some kind of displaySnackbar method on the Snackbar component? How can I call methods or functions on functional components?

I'm having real trouble understanding how React fits together. I'm maninly a backend developer but I've used JQuery and other Javascript frameworks in the past.

Any help much appreciated!

In React, you can only display things inside of render() . This means that you need to include the snackbar component inside of your render. You can use conditional rendering to decide whether to display them or not. Usually this is done by some value in the component state. You should initialize a state flag to false in the constructor and then call setState() in your fetch response code to set it to true .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM