The crossIcon on the MUI alert form won't let me close it

I am facing an issue with my snackBar and alert components from MUI. I am trying to close the alert using a function or by clicking on the crossIcon, but it's not working as expected. I have used code examples from MUI, but still can't figure out why it's not functioning properly. Any suggestions or ideas would be greatly appreciated, as I am new to React and MUI.

https://i.sstatic.net/Cc7OQ.png

import { useState } from 'react';

import CloseIcon from '@mui/icons-material/Close';
import { Alert, AlertTitle, IconButton, Snackbar, Typography } from '@mui/material';

interface InfoMessageProps {
  open: boolean;
}

export const InfoMessage = ({ open }: InfoMessageProps) => {
  const [openMessage, setOpenMesage] = useState(false);

const handleCloseMessage = (): void => {
  setOpenMesage(false);
};

  return (
    <Snackbar
      open={open}
      autoHideDuration={4000}
      anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
      onClose={handleCloseMessage}
    >
      <Alert
        sx={{
              width: '487px',
              height: '104px',
              paddingTop: '20px',
              paddingLeft: '20px',
              backgroundColor: '#FDFDFD',
        }}
        icon={false}
        action={(
          <IconButton
            aria-label="close"
            color="inherit"
            size="small"
            onClick={handleCloseMessage}
          >
            <CloseIcon fontSize="inherit" />
          </IconButton>
        )}
      >
        <AlertTitle sx={{ paddingRight:'80px' }}>
          <Typography variant='headings.h4'>title</Typography>
        </AlertTitle>
        <Typography variant='captions.default'>Insert message here</Typography>
      </Alert>
    </Snackbar>
  );
};

Answer №1

Your Snackbar is currently displayed because of the open prop. However, the state inside the InfoMessage component is not being updated. One solution is to pass a callback function from the parent component to the InfoMessage component in order to update the state.

function ParentComponent() {
  const [open, setOpen] = useState(true);

  return (
    <div>
      <InfoMessage open={open} onClose={() => setOpen(false)} />
    </div>
  );
}

You can then utilize this callback function in your InfoMessage component.

interface InfoMessageProps {
  open: boolean;
  onClose: () => void;
}

export const InfoMessage = ({ open, onClose }: InfoMessageProps) => {
  const [openMessage, setOpenMesage] = useState(false);

  return (
    <Snackbar
      open={open}
      autoHideDuration={4000}
      anchorOrigin={{ vertical: "top", horizontal: "right" }}
      onClose={onClose}
    >
      <Alert
        sx={{
          width: "487px",
          height: "104px",
          paddingTop: "20px",
          paddingLeft: "20px",
          backgroundColor: "#FDFDFD",
        }}
        icon={false}
        action={
          <IconButton
            aria-label="close"
            color="inherit"
            size="small"
            onClick={onClose}
          >
            <CloseIcon fontSize="inherit" />
          </IconButton>
        }
      >
        <AlertTitle sx={{ paddingRight: "80px" }}>
          <Typography variant="headings.h4">title</Typography>
        </AlertTitle>
        <Typography variant="captions.default">Insert message here</Typography>
      </Alert>
    </Snackbar>
  );
};

Answer №2

import { useState, useEffect } from "react";
import { Alert, AlertTitle, Fade } from "@mui/material";

export default function AlertBox() {

  const [alertVisibility, setAlertVisibility] = useState(true);

  useEffect(() => {
    setTimeout(() => {
      setAlertVisibility(false);
    }, 3000);
  });

  return (
    <Fade in={alertVisibility} timeout={{ exit: 1000 }}>
      <Alert
        onClose={() => {
          setAlertVisibility(false);
        }}
        severity="success"
        variant="filled"
        sx={{
          minWidth: 300,
          position: "absolute",
          zIndex: 100,
          bottom: 10,
          right: 10,
        }}
      >
        <AlertTitle>Warning</AlertTitle>
        Your message will go here
      </Alert>
    </Fade>
  );
};

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

Looping through multi-dimensional JSON objects with jQuery

Hello there, I'm currently facing some challenges in getting the screen below to work properly: Project progress screen I have generated the following JSON data from PHP and MYSQL. My goal is to display the project alongside user images and names whe ...

error detection in AJAX response handler

My web-application was created using PHP, AJAX, and jQuery, and the development process went smoothly. The majority of the requests to the application are made via AJAX for operations such as insert, update, delete, and select. I have already implemented ...

Update the inputs following the filtering or searching of issues in VueJS

As a newcomer to VueJS, I find myself struggling with a particular function and lack the experience to fully grasp it. To address my confusion, I have formulated a question (which may be similar to others). For instance, I utilized the computed propert ...

The scrollbar will be visible only when the mouse hovers over the table

I have been experimenting with customizing the scrollbar appearance of an ant design table. Currently, the scrollbar always displays as shown in this demo: https://i.stack.imgur.com/vlEPB.png However, I am trying to achieve a scroll behavior where the sc ...

retrieve the image name of the background using jQuery

How can I use jQuery to extract only the background image name from a div with a background image? I currently get 'http://localhost/xampp/uconnect/images/tour-networks-ss.png' but I only want 'tour-networks-ss.png' Any assistance wi ...

Transferring HTML variables to an Angular Component

I am currently trying to transfer the information inputted into a text-box field on my webpage to variables within the component file. These variables will then be utilized in the service file, which includes a function connected to the POST request I exec ...

How to extract query string parameters using node.js

I'm currently working on fetching query string parameters from a URL using the node.js restify module. This is an example of the URL I am dealing with: Here is the relevant code snippet: server.use(restify.bodyParser()); server.listen(7779, functi ...

The Value of Kendo Data

Below is my current kendo code snippet: <script> $("#dropdowntest").kendoDropDownList({ optionLabel: "Select N#", dataTextField: "NNumber", dataValueField: "AircraftID", index: 0, ...

What is the purpose of using the typeface Roboto?

Here is some React code for you to consider: import React, { Component } from 'react'; import ReactDOM from 'react-dom'; // Importing material-ui Typography import Typography from '@material-ui/core/Typography'; const App = ...

Getting Creative with Jquery Custombox: Embracing the 404

Encountering a problem with jquery custombox version 1.13 <script src="scripts/jquery.custombox.js"></script> <script> $(function () { $('#show').on('click', function ( e ) { $.fn.custombox( this, { ...

Angular Dom does not update when invoking a function within a separate component

Greetings everyone! I am facing a situation where one component (let's name it recipe component) has a reference to another component (named grocery component). The method in my recipe component uses the reference to the grocery component to call a s ...

Arranging an Array of Arrays Containing Strings

Looking for a solution to sort an array containing arrays of strings? A similar issue was discussed here. Here is the array in question: var myArray = [ ['blala', 'alfred', '...'], ['jfkdj', ...

What is preventing me from defining the widget as the key (using keyof) to limit the type?

My expectations: In the given scenario, I believe that the C component should have an error. This is because I have set the widget attribute to "Input", which only allows the constrained key "a" of type F. Therefore, setting the value for property "b" sho ...

Navigate to the AngularJS documentation and locate the section on monitoring data changes after a dropdown selection

Just starting out with AngularJS and Stack Overflow, so I hope I am asking this question correctly. I am working on a single-page application with editable text inputs. Two select drop-downs are used to control which data is displayed - one for time perio ...

Retrieve the value of a CSS class property regardless of whether it is actively being utilized

I am facing a dilemma where I need to determine the value of the 'width' property for a css class named 'foo' (example: ".foo { width:200px}" ). However, there may not be an element with this class in the dom yet. My goal is to retrie ...

Access denial encountered when attempting to submit upload in IE8 using JavaScript

When running the submit function on IE8, I am receiving an "access is denied" error (it works fine on Chrome and Firefox for IE versions above 8): var iframe = this._createIframe(id); var form = this._createForm(iframe, params); ... ... ...

Removing a field from a collection using firebase-admin: Tips and tricks

I currently have a collection stored in Firebase Realtime Database structured like this: https://i.sstatic.net/jNiaO.png My requirement is to remove the first element (the one ending with Wt6J) from the database using firebase-admin. Below is the code s ...

The shared module for next/router is not found in the shared scope default within Next.js and @module-federation/nextjs-mf

I am working on a JavaScript Turbo repo with a host app that has the following configuration in its next.config.js: const { NextFederationPlugin } = require("@module-federation/nextjs-mf"); const nextConfig = { reactStrictMode: true, ...

Showing hidden JavaScript elements in different parts of a webpage

Update: After making modifications to my JavaScript code, I am now encountering errors in the iPhone Debug Console. Disclaimer: As a newcomer to web development, I have limited expertise in JavaScript. Situation: My current project involves creating an e ...

It appears that when filtering data in Angular from Web Api calls, there is a significant amount of data cleaning required

It appears that the current website utilizes asp.net web forms calling web api, but I am looking to convert it to Angular calling Web api. One thing I have noticed is that I need to clean up the data. How should I approach this? Should I use conditional ...