The community of React Native offers a huge amount of ready to use libraries that can handle showing small messages called Toast. However, implementing it on our own is not a big effort. Additionally, we get full control of their behavior and look. Using Context API and hooks we can implement such a solution in no time.
First of all, we need to create context and Provider component:
in context, we have 3 available keys, two for manipulating toast visibility and one for getting state of toast
Now we need to create Consumer component:
here we use useContext
hook to get current toast state and we running Animation using useEffect
hooks. Additionally, we allow the user to close Toast when clicking on it.
Lets add some styles to our Toast component:
However, we can add auto-hidding into our Toast provider by adding useEffect
hook inside out ToastProvider
Now we can connect our provider and consumer to the App:
Yea! I know we can put Consumer login inside Provider and expose only show/hide method to context, but I want to have a more flexible solution (where I can put Consumer wherever I want in the application structure)
Now we can show our Toast from whatever screen we want:
And voila!
The whole working code you can find at https://github.com/Selleo/ReactNativeSimpleToastExample