What is the best way to implement the Snackbar functionality within a class-based component?

My snackbar codes are not working as expected when I click the "confirm" button. I want the snackbar to appear after clicking the button. Most examples I've seen use functional components, so how can I get the Snackbar to work properly in a class component?

class name extends Component {
  constructor() {
    super();
    this.state = { orders: [], open: false };
  }

  handleOpen = () => this.setState({ open: true });

  handleClose = () => this.setState({ open: false });

  columns = [
    {
      name: "Confirm",
      options: {
        customBodyRender: (value, tableMeta) => {
          return (
            <FormControlLabel
              value={value}
              control={
                <Button>
                  confirm
                </Button>
              }
              onClick={(e) => {
                try {
                  //firestore codes
                  );
                } catch (err) {
                  console.log(err);
                }
                this.handleOpen();
              }}
            />
          );
        },
      },
    },

  ];

   //code for options

   //data fetching codes
  
  render() {
    const { open } = this.state;
    return this.state.orders ? (
      <div>
        //muidatatable codes
        <Snackbar
          anchorOrigin={{
            vertical: "bottom",
            horizontal: "left",
          }}
          open={open}
          onClose={this.handleClose}
          autoHideDuration={2000}
          // other Snackbar props
        >
          Order Confirmed
        </Snackbar>
      </div>
    ) : (
      <p>Loading...</p>
    );
  }

}

Answer ā„–1

To ensure accuracy in checking for orders, it is recommended to use the length property of the array instead of solely relying on the existence of the array. When initializing an empty array like this.state.orders, simply using this.state.orders will always return true. It's better practice to utilize this.state.orders.length > 0 ? to validate if there are any orders present or not.

When working with Snackbar components, remember that the child elements should be wrapped in components rather than just plain strings. For direct string usage, make use of the message prop of the Snackbar component.

Additionally, adhere to naming conventions by starting a class name with an uppercase letter.

If you need a reference, here is a functional code snippet: Material UI Snackbar using classes

import React, { Component } from "react";
import { FormControlLabel, Button, Snackbar } from "@material-ui/core";
import MuiAlert from "@material-ui/lab/Alert";

export default class Name extends Component {
  constructor() {
    super();
    this.state = { orders: [], open: false };
  }

  handleOpen = () => this.setState({ open: true });

  handleClose = () => this.setState({ open: false });

  handleClick = () => this.setState({ orders: [1], open: true });
  columns = [
    {
      name: "Confirm",
      options: {
        customBodyRender: (value, tableMeta) => {
          return (
            <FormControlLabel
              value={value}
              control={<Button>confirm</Button>}
              onClick={(e) => {
                try {
                  //firestore codes
                } catch (err) {
                  console.log(err);
                }
                this.handleOpen();
              }}
            />
          );
        }
      }
    }
  ];

  //code for options

  //data fetching codes

  render() {
    const { open } = this.state;
    return (
      <>
        <Button variant="outlined" onClick={this.handleClick}>
          Open snackbar
        </Button>
        {this.state.orders.length > 0 ? (
          <div>
            <Snackbar
              anchorOrigin={{
                vertical: "bottom",
                horizontal: "left"
              }}
              open={open}
              onClose={this.handleClose}
              autoHideDuration={2000}
              // other Snackbar props
            >
              {/* <span
                style={{
                  background: "#000",
                  color: "#fff",
                  padding: "20px 5px",
                  width: "100%",
                  borderRadius: "5px"
                }}
              >
                Order Confirmed
              </span> */}
              <MuiAlert
                onClose={this.handleClose}
                severity="success"
                elevation={6}
                variant="filled"
              >
                Success Message
              </MuiAlert>
            </Snackbar>
          </div>
        ) : (
          <p>loading...</p>
        )}
      </>
    );
  }
}

Answer ā„–2

Implemented the necessary changes to ensure functionality:

  • Replaced Order Confirmed with the message prop of Snackbar
  • Added values to the orders array in the constructor
  • Set open variable to true

Shown below is the revised code for the snack bar feature.

import React, { Component } from "react";
import Snackbar from "@material-ui/core/Snackbar";

class SnackBarSof extends Component {
  constructor() {
    super();
    this.state = { orders: [1, 2], open: true };
  }

  handleOpen = () => this.setState({ open: true });

  handleClose = () => this.setState({ open: false });

  render() {
    console.log(this.state.orders);
    console.log(this.state);
    const { open } = this.state;
    return this.state.orders ? (
      <div>
        <Snackbar
          anchorOrigin={{
            vertical: "bottom",
            horizontal: "left",
          }}
          open={open}
          onClose={this.handleClose}
          message="order confirmed"
          autoHideDuration={2000}
        ></Snackbar>
      </div>
    ) : (
      <p>Loading...</p>
    );
  }
}

export default SnackBarSof;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with React Router: the value of this.props.location.state is currently absent

Currently, I am utilizing react-router version 2.4.0. My goal is to pass some state to my route upon a click event. While it successfully passes in the pathname and query, unfortunately, the state ends up being null. Here is the snippet of my handler func ...

What is the process of returning a JSX object using I18Next?

The issue arises when attempting to incorporate NavLink elements into this string. Below are the elements and where I am expecting a string with links. const termsOfUseLink = ( <NavLink to="/terms-of-use" target="_blank"> ...

Optimizing Angular for search engines: step-by-step guide

Regarding Angular SEO, I have a question about setting meta tags in the constructors of .ts files. I have implemented the following code: //To set the page title this.titleServ.setTitle("PAGE TITLE") //To set the meta description this.meta.addTag ...

What are the steps to resolve the "undefined cannot read property push" error in Node.js?

While attempting to learn Nodejs, I created a simple app. However, when I run "nodemon index.js" in the command prompt, I encountered the following error: TypeError: Cannot read property 'push' of undefined The app crashed and is now waiting for ...

Steps to resolve eslint error in cases of using the node: protocol for importing Node.js built-in modules

Can someone guide me on what to include in my .eslintrc file for my specific situation? Link 1 Link 2 If I disable this rule, I encounter the following error: import path from "path"; // ESLint: Prefer `node:path` over `path`.(unicorn ...

Discovering the Active Modal Form in BootStrap: Uncovering the Open Modal Form using JavaScript/jQuery

There are a total of 5 modal forms on my page. My goal is to identify the specific Id of the currently active one. One possible solution involves checking if $('#myModal').hasClass('in');. However, this method requires me to repeat the ...

Having an issue while running the command "npm start" in Visual Studio with React.js

PS C:\Users\PC1\Downloads\portfolio_website-STARTER> npm start > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d0d120f091b12111412220a181f0e140918500e091c0f09180f3d4c534d534d">[email protect ...

Patience is key when waiting for both subscriptions to be completed before proceeding with an

I am facing a challenge with two subscriptions as shown below: this.birthdays = await this.birthdaySP.getBirthdays(); this.birthdays.subscribe(groups => { const allBirthdayT = []; groups.map(c => { allBirthdayT.push({ key: c.pa ...

A quick guide on automatically populating text boxes with characteristics of the item chosen from a drop-down menu

On my webpage, I am looking to automatically populate textboxes with information (such as common name, location, etc.) of the selected shop from a dropdown list without having to refresh the page. Here is the dropdown list: <select id="shops" class="f ...

Tips for exploring electron without launching additional windows

Is there a way to navigate between HTML pages within the same window without opening multiple windows in Electron? ...

Want to learn about Google Apps Script Web App? Join us to dive into AJAX, leverage

I'm attempting to follow the steps outlined in "Example 3: Web Response" on "this SparkFun tutorial" After implementing the code on script.google.com, I encountered an issue where I couldn't see the pin readings. Can someone provide assistance w ...

Guide on utilizing JavaScript to modify the attribute of a chosen web element with Selenium WebDriver in Java

I am seeking a way to utilize Javascript in order to set attributes for the selected element on a webpage. After some research, I have discovered two methods for achieving this with Javascript: Method 1 WebDriver driver; // Assigned elsewhere Jav ...

Ways to effectively utilize jQuery objects as arguments in the delegate function

When working with delegate and multiple selectors, you can use the following syntax: $(contextElement).delegate('selector1, selector2' , 'eventName', function(){ //blabla }); In projects where managing DOM elements is important, stori ...

What is the best method for enclosing all text within an HTML document with a different element?

For example: FROM <div> whats up! <div> whats up2! </div> thank you for your help <div></div> </div> TO <div> <span>whats up!</span> <div><span> whats up2! </span&g ...

Enhancing the appearance of the Switcher by framing it with

I've been working with the component package https://www.npmjs.com/package/react-switch-selector to create a design similar to this https://i.stack.imgur.com/voHqm.png Although I have made some progress, I'm struggling to add a border outline. H ...

Updated Multer version causing issues with uploading image files

After using multer middleware to upload an image, I encountered an issue where the file image was showing up as undefined. This meant that I couldn't retrieve the name or file extension of the uploaded file. I'm not sure if this is an error with ...

When a user clicks on an element, use jQuery to show a specific

I am looking to extract the Admission ID field within a separate function that triggers when a user clicks on a button. $(document).ready(function () { $.each(data.student, function (i, item){ trHTML += '<tr>'+ ...

Enable/Disable Text Editing Based on Vue Js Input

Iā€™m working on a way to make certain parts of a string in an input editable or non-editable (readonly) depending on the context in Vue.js. For instance: I have this text: My Name is $John Doe$ Now, I want my Vue.js code to scan the string and allow edi ...

Achieving a Subset Using Functional Programming

Looking for suggestions on implementing a function that takes an array A containing n elements and a number k as input. The function should return an array consisting of all subsets of size k from A, with each subset represented as an array. Please define ...

Updating the MLM binary tree system

In my JavaScript nested object, the IDs of objects increase in depth. By using JavaScript support, I added an object inside ID - 2 with a children array of 3. What I need is to update (increment) the IDs of all siblings in the tree. This code snippet shoul ...