3

I created a component called Alertify.js

import React, {useEffect, useState} from "react";
import { Alert } from 'reactstrap';

function Alertify(props){

    const [show, setShow] = useState(props.show);

        useEffect(
            () => {
                let timer = setTimeout(() => setShow(false), 3000);
                return () => {
                    clearTimeout(timer);
                };
            },
            []
        );

    return (
        <Alert color={props.color} className={show ? 'float active' : 'float'}>{props.text}</Alert>
    )
}

export default Alertify;

And used in index.js

import Alertify from "../Component/Alertify";
const [showAlert, setShowAlert] = useState(false);
return...
<Alertify text={'hello world'} color={'danger'} show={showAlert}/>

And it will show this alert after a condition is true:

if(condition){
setShowAlert(true)
}

But something is wrong and not show alert on condition, and I'm newbie to reactjs, any idea how to fix this? All I want is show alert after condition is true, then hide after 3 seconds.

Also it show if I remove useEffect but before condition true, and also not hiding.

2
  • Where and how is this condition being applied, please? Edit: also, I'm not sure about your use of useEffect, since (from the code you have provided) show seems to be false when the component is rendered. Commented Jan 10, 2022 at 23:35
  • @thebigfundamentals Easily. after click a button in index.js inside this condition I used setShowAlert(true) Commented Jan 12, 2022 at 8:00

2 Answers 2

1

Try the following

const [show, setShow] = useState(false);

useEffect(() => {
  if (props.show) {
   setShow(true)
  }
},[props.show])

You can leave your existing useEffect to clear after 3 seconds as is.

EDIT:

Here's a modified approach, your Alertify component looks like so

import React, { useEffect, useState } from "react";
import { Alert } from "reactstrap";

function Alertify(props: {
  show: any;
  color: string;
  text: boolean | React.ReactChild | React.ReactFragment | React.ReactPortal;
  setShowAlert: (value: boolean) => void;
}) {
  const [show, setShow] = useState(false);

  useEffect(() => {
    let timer = setTimeout(() => {
      return setShow(false);
    }, 3000);
    return () => {
      clearTimeout(timer);
    };
  });

  useEffect(() => {
    if (props.show) {
      setShow(true);
      props.setShowAlert(false);
    }
  }, [props.show, props.setShowAlert]);

  if (show) {
    return (
      <Alert color={props.color} className={show ? "float active" : "float"}>
        {props.text}
      </Alert>
    );
  }

  return null;
}

export default Alertify;

Your calling component then looks like so

import "./styles.css";
import Alertify from "./Alertify";
import { useState } from "react";

export default function App() {
  const [showAlert, setShowAlert] = useState(false);
  return (
    <>
      <div className="App">
        <Alertify
          text={"hello world"}
          color={"danger"}
          show={showAlert}
          setShowAlert={setShowAlert}
        />
      </div>
      <button onClick={() => setShowAlert(true)}>show alert</button>
    </>
  );
}

Here's the codesandbox link https://codesandbox.io/s/alertify-stackoverflow-x096t

Sign up to request clarification or add additional context in comments.

3 Comments

Actually I didn't understand your answer, can you explain more and insert complete codes here?
@tourtravel please see my edit above. I've also created a codesandbox.
Thanks it works fine, just it not show css animation by switching between classes, I mean it show softly (fade) but disappeared after 3scs, but it enough for me and I accepted. Thanks for your help.
0

Try this code. You can control rendering Alertify component in index.js. If showAlert value is true, React render Alertify component. When setTimeout executed, showAlert value will be false which means React unmount Alertify component. This is like show and hide effect as what you need.

// index.js
import Alertify from "../Component/Alertify";
const [showAlert, setShowAlert] = useState(false);

if (condition( {
  setShowAlert(true); // This makes Alertify component mount immediatly.
  setTimeout(setShowAlert(false),3000); // This makes Alertify component unmount in 3,000ms.
}

return...
{showAlert && <Alertify text={'hello world'} color={'danger'}/>}

Therefore, you don't need to use useEffect to make this component hide.

// Alertify.js
import React, {useEffect, useState} from "react";
import { Alert } from 'reactstrap';

function Alertify(props){

    return (
        <Alert color={props.color} className={'float active'}>{props.text
        </Alert>
    )
};

export default Alertify;

1 Comment

But I want to make a component, don't want to hide alert after 3000 ms in every page I use , It should hide in own component , you just used to hide it in index.js but if I want to use this comp in another page, like x.js, I should hide it again, actually it should be in alertify.js

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.