I am dealing with a form taking input and am validating it. I want to show the validation error that a function returns using Toasts. Its quire redundant to go toast({}) and write down the status (success,error,etc) and the message for each type. Further on I will have to re write the same code in case I use another form in the website.
What i was thinking was to make a component that returns the toast and i just have to pass the status and message to it, but I cant figure out how to do so.
I am using chakra-ui but react solution of the same would also suffice for further projects.
I have tried this:
import { Button, useToast } from "@chakra-ui/react"
import Toast from "../Components/Toast"
export default function Abc() {
const toast = useToast()
const ToastDisplay = () =>{
return (
{Toast}
)
}
return (
<>
<Button onClick={()=>{ToastDisplay()}}>
show toast
</Button>
</>
)
}
Toast.jsx file:
import { useColorMode } from '@chakra-ui/react';
import { useToast } from "@chakra-ui/react"
export default function Toast() {
const toast = useToast();
const optionsForToast = {
position: "bottom-right",
autoClose: 300,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "dark"
}
console.log(optionsForToast)
return (
toast({
title:"hii"
})
)
}
I have tried directly using Toast function that is imported inside onClick in this way:
onClick={()=>{Toast()}}
It gives me an error in the console-
Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
I have also tried replacing with <Toast /> both inside onClick and the ToastDisplay function (removes the error).
Further replacing ToastDisplay()
with ToastDisplay
also removes the error from console but doesnt render the Toast.