timolins / react-hot-toast

Smoking Hot React Notifications 🔥
https://react-hot-toast.com
MIT License
9.66k stars 319 forks source link

Set positions based on breakpoints for Responsive Design. #216

Closed leidsoncruz closed 2 years ago

leidsoncruz commented 2 years ago

It would be great to define positions for different breakpoints. For example, on a PC, tablets, and big screens, we could have the toast in the bottom right. But, for mobile, we want to have it in the middle of the screen.

I can create a hook to control that, but it'll not be a built-in feature.

import { useState, useEffect } from 'react';

const useMedia = (query: string) => {
  const [matches, setMatches] = useState(window.matchMedia(query).matches);

  useEffect(() => {
    const media = window.matchMedia(query);
    if (media.matches !== matches) {
      setMatches(media.matches);
    }
    const listener = () => setMatches(media.matches);
    media.addEventListener('change', listener);
    return () => media.removeEventListener('change', listener);
  }, [query, matches]);

  return matches;
};

export default useMedia;

...
  const small = useMedia("(max-width: 640px)");
...
      <Toaster position={small ? "bottom-center" : "bottom-right"} />
timolins commented 2 years ago

Hi @leidsoncruz. Thanks for your suggestion. To keep things simple, I prefer to keep this logic outside the library.

For reference, this codesandbox showcases a similar hook to yours: https://codesandbox.io/s/react-hot-toast-responsive-position-with-breakpoints-rh276