Search code examples
reactjstypescriptchakra-ui

Chakra UI: Responsive Toast Notifications


I'm using chakra UI for my application and this is the code block I'm calling to display the notification.

const successToast = useToast({
    title: 'Logged In',
    description: "Waiting for developers to build redirect pages",
    status: 'success',
    duration: 5000,
    isClosable: true,
    position: "bottom-right",
  })

Chakra offers a way to handle responsive designs: https://chakra-ui.com/docs/features/responsive-styles. So I want the notification to be shown on top when using a mobile device. For which I tried doing:

position: {base: 'top-right', lg:'bottom-right'}

But I get error saying:

(property) UseToastOptions.position?: ToastPositionWithLogical | undefined
The placement of the toast

@default

"bottom"
Type '{ base: string; lg: string; }' is not assignable to type 'ToastPositionWithLogical | undefined'.
  Type '{ base: string; lg: string; }' is not assignable to type '"bottom-right"'.

Previously when I used this method to make other design elements it worked. How do I fix it or make it responsive for this.

Toast Notification Docs: https://chakra-ui.com/docs/feedback/toast


Solution

  • You could use the useBreakpointValue hook.

    const position = useBreakpointValue({ base: 'top-right', mlg: 'bottom-right' }) as any;
    
    function displayToast(){
        const successToast = useToast({
        // [...]
        position: position,
      })
    }
    

    Edit: Added as any as position accepts only ToastPositionWithLogical