Search code examples
reactjstypescriptreact-toastify

React-toastify :Addition of the colored theme in the toast options


I use react-toastify to display my toast, I created a component that allows me to display the toast according to the type.

import {
  Slide,
  toast
} from 'react-toastify';

const options = {
  autoClose: 5000,
  position: toast.POSITION.TOP_CENTER,
  transition: Slide,
  closeOnClick: true,
  closeButton: false,
};

const Alert = (type: string, message: string) => {
  switch (type) {
    case 'warning':
      return toast.warning(message);
    case 'error':
      return toast.error(message, options);
    case 'success':
      return toast.success(message);
    case 'info':
      return toast.info(message);
    case 'dark':
      return toast.dark(message);
    default:
      return toast(message);
  }
};

export default Alert;

And I call it like this:

Alert('error', 'Try Again');

options determine all the options I want to configure. But if I add in the options theme: 'colored', I end up with the following message.

Argument of type '{ autoClose: number; position: ToastPosition; transition({ children, position, preventExitTransition, done, nodeRef, isIn }: ToastTransitionProps) => JSX.Element; closeOnClick: boolean; closeButton:boolean; theme: string; }' is not assignable to parameter of type 'ToastOptions<{}>'.

Types of property 'theme' are incompatible.
Type 'string' is not assignable to type 'Theme | undefined'.

On the other hand if I make the call differently

case 'error':
  return toast.error(message, {
    theme: 'colored',
  });

I have no error message.

How to ensure that the theme is present in the options apply without error?


Solution

  • You should declare theme props in ToastContainerProps interface of react-toastify library, either in the root component or in declaration.d.ts file

    declare module 'react-toastify' {
      export interface ToastContainerProps {
        theme?: string
      }
    }