How can I make my alert automatically disappear after 2 seconds in React.JS? Currently, the alert only disappears when I manually close it using the fecharAlerta props function.
import { useEffect } from "react"
import { useState } from "react"
import { FaCheck, FaExclamationTriangle, FaInfo, } from "react-icons/fa"
import { HiX } from "react-icons/hi"
import "./css/alerta.css"
function Alerta({ tipo, mostrar, mensagem, fecharAlerta }) {
const [cor, setCor] = useState()
useEffect(function () {
if (tipo === "sucesso") {
setCor("rgb(74, 112, 74)")
}
if (tipo === "erro") {
setCor("rgb(138, 67, 67)")
}
if (tipo === "info") {
setCor("rgb(185, 184, 93)")
}
}, [tipo])
if (mostrar === true) {
// Code to make alert disappear after 2 seconds goes here
return (
<div className="alerta" style={{ backgroundColor: cor }}>
{tipo === "sucesso" &&
<FaCheck className="icon" />
}
{tipo === "erro" &&
<FaExclamationTriangle className="icon" />
}
{tipo === "info" &&
<FaInfo className="icon" />
}
<span className="titulo">{mensagem}</span>
<div><button className="fechar-btn" onClick={fecharAlerta}><HiX /></button></div>
</div>
)
}
else {
return null
}
}
export default Alerta