I found useToast and useToastContainer, but documentation is absent and i don't understand how tu use these hooks. Can anyone provide some info about these hooks?
Asked
Active
Viewed 9,931 times
3
-
did you went through this: https://www.npmjs.com/package/react-toast-notifications – Abu Sufian Jul 09 '20 at 17:54
1 Answers
1
The toasts
inherit ToastContainer’s
props. Props defined on toast supersede ToastContainer’s props.
There are two ways you can use toasts
in your application:
1. Define
ToastContainer
inside the component
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
const App = () => {
notify = () => toast("Wow so easy !");
return (
<div>
<button onClick={notify}>Notify !</button>
// You can add <ToastContainer /> in root component as well.
<ToastContainer />
</div>
);
}
2. Call
toast.configure()
once in your app. At theroot
of your app is the best place.
The library will mount a ToastContainer
for you if none is mounted.
import { toast } from "react-toastify";
import 'react-toastify/dist/ReactToastify.css';
// Call it once in your app. At the root of your app is the best place
toast.configure()
const App = () => {
notify = () => toast("Wow so easy !");
return (
<button onClick={notify}>Notify !</button>
);
}
You can use either of them. I prefer the 2nd method because you only need to define toast.configure()
which is quite clean way to add it.
You can add configuration as per your need like below:
toast.configure({
autoClose: 8000,
draggable: false,
//etc you get the idea
});
EDIT
If you want to use toast hooks, then you must wrap your app with the ToastProvider to have access to its context elsewhere within your app.
import { ToastProvider, useToasts } from 'react-toast-notifications'
const FormWithToasts = () => {
const { addToast } = useToasts()
const onSubmit = async value => {
const { error } = await dataPersistenceLayer(value)
if (error) {
addToast(error.message, { appearance: 'error' })
} else {
addToast('Saved Successfully', { appearance: 'success' })
}
}
return <form onSubmit={onSubmit}>...</form>
}
const App = () => (
<ToastProvider>
<FormWithToasts />
</ToastProvider>
)

harish kumar
- 1,732
- 1
- 10
- 21
-
1You can't define ToastContainer and use toast() from custom hook, that's the problem. If you know how to use it, i will be very happy. – cikpak Jul 11 '20 at 09:49
-
1you must wrap your app with the ToastProvider to have access to its context elsewhere within your app. https://github.com/jossmac/react-toast-notifications#use – harish kumar Jul 11 '20 at 11:12
-