Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setTimeout for my custom toast on React?

The idea is simple: By the time showToast function is executed, I want to set my toast's className to show, and then replace it with an empty string to hide it after showing it for 3 secs.

HTML:

<div id="toast">New color button added</div>

JS:

const showToast = () => {
    const toast = document.getElementById('toast');
    toast.className = 'show';
    setTimeout(() => {
        toast.className = toast.className.replace('show', '');
    }, 3000);
};

I'm trying to convert this into a React component:

import React, { useState } from 'react';

const Toast = () => {
    const [isShown, setIsShown] = useState(true);

    setTimeout(() => {
        setIsShown(!isShown);
    }, 3000);

    return (
        <div className={isShown ? 'show' : undefined}>New color button added</div>
    );
};

export default Toast;

And then I'm going to have this in a function by the time I need to show it:

<Toast />

But I'm not sure if this is correct. I honestly don't know how to do this. Please help.

like image 774
Zedd Avatar asked Dec 07 '25 03:12

Zedd


1 Answers

Based on React-toastify documentation you are able to pass the time by using autoClose variable as below:

<ToastContainer
position="top-right"
autoClose={5000}
hideProgressBar={false}
newestOnTop={false}
closeOnClick
rtl={false}
pauseOnFocusLoss
draggable
pauseOnHover
theme="light"
/>
{/* Same as */}
<ToastContainer />

Or

toast('🦄 Wow so easy!', {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
});
like image 66
hussam alhunaiti27 Avatar answered Dec 08 '25 18:12

hussam alhunaiti27