Oye, estaba puliendo mi aplicación desde que finalmente la terminé y pensé que sería mejor reemplazar todas las alertas de window.alerts para Alerts from MUI (porque se ven mucho mejor) sin embargo, parece que no aparece por alguna razón. ?
Entonces, por ejemplo, tengo que cuando las contraseñas no coinciden, envía un mensaje:
const register = (e) => { if(password !== confirmsPassword){ alert("Las contraseñas no coinciden"); } else if(password.length < 6){ alert("Su contraseña debe tener al menos 6 caracteres"); } else{ //Some smart and long code that updates the information to the firebase } }Y eso funciona, aparece lo siguiente:
Sin embargo, cuando trato de usar Alertas de MUI:
const register = (e) => { if(password !== confirmsPassword){ <Alert severity="error">Las contraseñas no coinciden</Alert> } else if(password.length < 6){ <Alert severity="error">Su contraseña debe tener al menos 6 caracteres</Alert> } else{ //Some smart and long code that updates the information to the firebase } }no hace nada en absoluto, ningún mensaje, ninguna alerta, nada. Este es el enlace Alerta MUI
Respuesta basada en MUI.
Entonces, después de algunos intentos, encontré una solución usando componentes MUI y es una mezcla entre los componentes Alerts, Snackbar, MuiAlert
Básicamente, haga otro componente, para este ejemplo será InstantMessage.js
import React, {useState, forwardRef} from 'react' import Snackbar from '@mui/material/Snackbar'; import MuiAlert from '@mui/material/Alert'; const Alert = React.forwardRef(function Alert(props, ref) { return <MuiAlert elevation={6} ref={ref} variant="filled" {...props} />; }); const InstantMessage = ({message}) => { const [open, setOpen] = useState(true); //Leave this true since we are not using a button const handleClose = (event, reason) => { if (reason === 'clickaway') { return; } setOpen(false); }; return ( <Snackbar open={open} autoHideDuration={6000} onClose={handleClose}> <Alert onClose={handleClose} severity="error">{message}</Alert> </Snackbar> ) } export default InstantMessageY luego en el componente que desea utilizar las alertas:
//Initialize you can call it alerts or w/e you want //I'll use error cause I only catch errors in this piece of code. import InstantMessage from './InstantMessage '; const [error, setError] = useState(false); //Controls Alert const [message, setMessage] = useState('') //Controls Message so for example I have a register function with firebase: const register = (e) => { e.preventDefault(); auth.createUserWithEmailAndPassword(email, password).then((auth) => { if(auth.user){ //Some smart code } }).catch((e) => { if(e.message === "Some error example"){ setMessage("some alert") setError(true); // Turn On Alert so it displays } }); setError(false); //very important to set this back to off }Finalmente, en algún lugar de su procesamiento/retorno, agregue la siguiente declaración:
//if error then call component InstantMessage and send the prop message {error ? <InstantMessage message = {message} /> : `` }Al final debería verse así: