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

Why is TS1005 triggered for Redux Action Interface with an expectation of '=>'?

I'm finding it difficult to identify what's causing this issue, as shown in the esLint error from Typescript displayed in the screenshot below: https://i.stack.imgur.com/pPZa7.png Below is the complete code, which consists of actions for redux. ...

Setting a bookmark feature in HTML using localStorage: A step-by-step guide

I'm working on a simple code that captures the text content of a dynamically updated <h1> element and stores it as a "bookmark" in localStorage. I want to enable users to save or delete the bookmark by clicking a button. Below is a basic version ...

What is the best way for me to use a ternary operator within this code snippet?

I'm in the process of implementing a ternary operator into this snippet of code, with the intention of adding another component if the condition is false. This method is unfamiliar to me, as I've never utilized a ternary operator within blocks of ...

Encountering Unmet Dependency Issue When Running 'npm install' on Laravel in Windows 8

Currently, I am in the process of working on a Laravel project and looking to utilize Elixir to handle my front-end tasks. After running 'npm install', I encountered a warning stating "npm WARN unmet dependency". What steps should I take in order ...

Looking for help in resolving console error displaying 'Uncaught (in promise)' notification

I've encountered an issue while trying to troubleshoot a problem that involves using the find() method, which is causing an error. import { CART_ADD_ITEM, CART_REMOVE_ITEM } from '../constants/cartConstant'; const cartReducers = (state = { ...

"An error occurred with the Google chart due to 'null' not being recognized as an object, specifically in relation to the select menu and onchange event

Currently, I have implemented the following Script: <header> <script type="text/javascript" src="http://www.google.com/jsapi"></script> </header> <body> <script type="text/javascript"> google.load("visualization", "1 ...

Cypress - Locate and interact with a button containing specific text

Utilizing material-ui as my go-to css framework, I'm seeking to target a button that includes specific text. Here is my current code: cy.get('button').contains('Edit Claim').should('be.disabled'); The issue arises becaus ...

How can I programmatically adjust the center of a Google Maps v3 map?

I have a table with 2 columns. The first column contains a div with a Google map, while the second column has a panel that changes its width after a few seconds. On the map, there is a marker placed. Issue: When I click on a button that triggers setCente ...

Error: Attempting to use hooks outside the scope of a function component in react-native. Hooks can only be called within the body of a

Oops! An error occurred: Invalid hook call. Hooks can only be called inside the body of a function component. There are several reasons why this might have happened: You could have incompatible versions of React and the renderer (e.g., React DOM) Your cod ...

WebStorm not recognizing NodeJS Core Modules in External Libraries

As a newcomer to NodeJS and WebStorm, I am currently diving into a tutorial on creating an Express app. In the tutorial, the instructor always gets prompted with "Configure NodeJS Core Module Sources" including the URL nodeJS.org when creating a new NodeJ ...

What is the best practice for importing React components?

In my experience with React, I've noticed two different ways of importing and extending components. The first way that I typically use is shown below. import React from 'react'; class SomeClass extends React.Component { //Some code } ...

Comparing obj.hasOwnProperty(key) with directly accessing obj[key]

Consider the scenario where I need to determine if a property exists within an Object. A comparison between two methods caught my attention: if(object.hasOwnProperty(key)) { /* perform this action */ } OR if(object[key]) { /* perform this action */ ...

How can multiple arguments be passed to a function using JQuery's post method?

I can't seem to figure out how to pass multiple arguments to a function using jQuery's post method. It might sound like a silly question, but I'm struggling with it. Currently, my code looks something like this: $.post("<?php echo site_ ...

What are the steps to integrate and utilize DefinePlugin within your webpack configuration?

Hello, I'm currently trying to implement the DefinePlugin in order to update the version number and ensure that my JavaScript refreshes after a new build is released. Unfortunately, I am encountering issues with getting DefinePlugin to work properly. ...

The ng-model is not properly syncing values bidirectionally within a modal window

I am dealing with some html <body ng-controller="AppCtrl"> <ion-side-menus> <ion-side-menu-content> <ion-nav-bar class="nav-title-slide-ios7 bar-positive"> <ion-nav-back-button class="button-icon ion-arrow-le ...

Having trouble showing a card image from a URL using Material UI and the CardMedia component?

I created a blog app with a Material UI card component to showcase the latest post on the home screen. However, I am facing an issue with getting the image to display. The data for my posts and image URLs are stored in a JSON file. My goal is to extract th ...

Having trouble getting react-router-dom v6 NavLink to work alongside MUI ListItem and className?

Having trouble getting MUI to work with react-router-dom v6. import ListItem from '@mui/material/ListItem'; import { NavLink } from 'react-router-dom'; <List key={index}> <ListItem component={NavLink} sx={{ ...

The jQuery function may encounter issues when trying to target elements within an appended HTML form

I am encountering a couple of issues. I have 2 separate JQuery functions, one for appending content and the other for displaying the selected file's name. FUNCTION 1 <script> jQuery( document ).ready(function( $ ) { $("input[name ...

Vue.JS and its Onclick event handler allows for dynamic and interactive

These are my two buttons: <button onclick="filterSelection('Action')">Action</button> and <button onclick="filterSelection('Adventure')">Adventure</button> Now, I'm trying to achieve the same fun ...

Guide to incorporating a variable into the hyperlink function with Google Apps Script

Currently, I am utilizing Google Apps Script to create customized reports within Google Sheets. Within my spreadsheet, there is a column consisting of numbers that I would like to transform into hyperlinks. The URL for each hyperlink is mostly the same, wi ...