React.JS Tip: Automatically Make Alerts Disappear in 2 Seconds!

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

Answer №1

To implement the dismissal feature, a new useEffect hook is utilized.

In the updated code, the second useEffect hook handles setting up a timeout when the component is mounted. It employs the setTimeout function to schedule the execution of the fecharAlerta callback after 2000 milliseconds (2 seconds). This ensures that the alert will automatically close after the specified time duration.

In order to clean up the timeout and prevent any memory leaks, the useEffect hook returns a cleanup function which invokes clearTimeout with the reference to the timeout. This guarantees that the timeout is cleared if the component gets unmounted.

import { useEffect, 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(() => {
    if (tipo === "sucesso")
      setCor("rgb(74, 112, 74)");
    else if (tipo === "erro")
      setCor("rgb(138, 67, 67)");
    else if (tipo === "info")
      setCor("rgb(185, 184, 93)");
  }, [tipo]);

  useEffect(() => {
    const timeout = setTimeout(fecharAlerta, 2000);
    return () => clearTimeout(timeout);
  }, [fecharAlerta]);

  return mostrar ? (
    <div className="alerta" style={{ backgroundColor: cor }}>
      {tipo === "sucesso" ? <FaCheck className="icon" /> : null}
      {tipo === "erro" ? <FaExclamationTriangle className="icon" /> : null}
      {tipo === "info" ? <FaInfo className="icon" /> : null}
      <span className="titulo">{mensagem}</span>

      <div>
        <button className="fechar-btn" onClick={fecharAlerta}>
          <HiX />
        </button>
      </div>
    </div>
  ) : null;
}

export default Alerta

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

Having difficulty retrieving the user list from Firebase within Angular 6

I am facing an issue with retrieving the list of users from Firebase. Despite having values already set in the database, I am getting empty arrays. The strange thing is that I can successfully add users to the Firebase database and retrieve the list of us ...

Having trouble with axios calls being caught in the catch block when mocking it in Jest

When my component loads, the useEffect function triggers an axios.get request to fetch user data and displays it on the page. However, I'm having trouble replicating this behavior in Jest. Every time I try, I end up in the catch block and the data ke ...

What is causing the regular expression to fail when using the OR operator?

Here is the code snippet I've been working on: function toCamelCase(str){ var rest = str.replace((/-/)|(/_/)g, "") ; document.write(rest); } toCamelCase("the-stealth_warrior"); When running this code, I receive an error message: Uncaught Syntax ...

Display or conceal objects within a 3D model with an HTML checkbox

I have utilized JavaScript, CSS, and Three.js to create a 3D model. The project comprises a total of 5 JS files, 1 CSS file, and 1 HTML file. Here is an overview of the model: [] Showers have been incorporated for each cubicle, which should only be vis ...

Spinning points about a center point

My goal is to rotate 4 points around a specific origin. Initially, the points appear in the correct position without any rotation. The code for this initial positioning is as follows: let origin = this.transform.position; for (let i in this._pointsOrig) { ...

Is it possible to modify styling programmatically in a React Native application?

I was wondering if it is achievable in react native to assign a style to a variable that relies on the response of an API call? For instance let textColor = 'fake-api-getcolor' <text style={{color: textColor}}>Hello</text> Then, ...

Please ensure that there is a minimum of one checkbox with nested names

Update: After some troubleshooting, I discovered that my additional method was not being triggered due to calling addClassRules for my form class. To work around this issue, I included a hidden form field with no value and applied the custom validation to ...

What is the best way to send props and trigger a function with a single onclick event?

Is there a way to receive a prop and activate a function using the same onclick event? In the navbar.js file, the props are passed like this: <Hamburger menuOpen={this.ToggleMenu} /> In the Hamburger.js file, the props are received. Currently, the ...

No matter how many times I modified the code in the ReactDOM.render() method within my index.js file, the end result remained unchanged

When I ran npx create-react-app my-app, and then proceeded to cd my-app and npm start, a browser opened on localhost:3000. While looking at the index.js file, I noticed that the ReactDOM.render() method included the following code: ReactDOM.render( <Rea ...

Issue with IE6: Div inside Anchor element causing inline images to not be clickable links

I am currently facing an issue where I need everything within the anchor tag to be a clickable link, but in IE6 (the only browser I am concerned about at the moment), the inline images are not clickable. I understand that it is not valid HTML to place a di ...

Is there a way for me to record the variable's name instead of its linked data?

Currently, I am developing a node.js program that monitors the prices of different currencies. While I can successfully retrieve the prices, I would like the program to also display the names of the currencies along with their prices. In the code snippet b ...

Issues arise when attempting to toggle the Angular Bootstrap 4 navbar, along with challenges related to the navbar-dark feature

Whenever I attempt to click the hamburger icon to toggle the navigation on a small screen width, nothing happens. I've tried looking for solutions in previous questions, but I can't seem to find where my error lies. Moreover, when I remove th ...

Transferring a variable from template.php to a javascript file

Within my THEME_preprocess_page function, I am using the following code: drupal_add_js(array('variableName' => 'value'), 'setting'); Then, in my JavaScript file: alert(Drupal.settings.variableName); However, I am receiv ...

Extracting individual elements from an array with Node.js or JavaScript

let array1= [ "home/work/data.jpg", "home/work/abc.jpg", "home/work/doc/animal.pdf", "home/work/doc/fish_pdf.pdf" ]; array1= array1.map((data)=>{ return data.slice(2,data.length).join("/"); }); console.log(array1); i am trying to modify my array by re ...

What methods can be used to extract an element's contents prior to its attachment?

Looking for a way to insert an html string directly into an element, but with the need to add a path to certain 'src' attributes of image tags. Currently, my approach involves: // Note: the htmlString is sourced from an external XML file... var ...

Ensure consistency of wrapper height across various browsers

Ensuring consistent height for a wrapper across all browsers is proving to be a challenge. Methods such as using min-height and setting height to 100% have been attempted, but unfortunately, results are not as intended. So how can this issue be resolved? ...

Issue with React Portal not rendering children within a functional component

After successfully creating a React portal component using a class component, I decided to rewrite it as a functional component. However, after making the switch, the portal now only generates a div inside another div with the ID #portal, but no children ...

Best practices for incorporating JavaScript into Angular applications

I am looking to integrate a JavaScript library into my Angular application. After researching various methods, I have decided to incorporate the library found at . I was hoping to create a module named 'plot-function' that would offer a function ...

Ensuring correct association of values to avoid redundancies

There are 5 fields available for users to fill out on this form: Leave Code, From Date, Input Time1, To Date, and Input Time2. These variables are declared as a dates object in the .ts file, as shown below. interface Supervisor { name: string; code: s ...

Timeout causes failure in AngularJS jasmine promise testing

I need help testing my login controller, here is the structure of it: describe('LoginController', function() { beforeEach(module('task6')); var $controller, LoginService; beforeEach(inject(function(_$controller_, _LoginSe ...