Search code examples
reactjstypescripttransitionreact-bootstraptoast

How to use TransitionComponent in React-Bootstrap


I'd like to set transition props for ToastContainer to use transition animation for Toast notification.

transition should be TransitionComponent.

TransitionComponent looks like this;

export declare type TransitionComponent = React.ComponentType<{
    in?: boolean;
    appear?: boolean;
} & TransitionCallbacks>;
export declare type TransitionType = boolean | TransitionComponent;

I'd like to set transition like below;

export const Toast = ({ message, onClose }: Props) => {
  const messageRef = useRef<{
    head: string;
    body: string;
    detail?: string;
  }>({ head: "", body: "" });

  if (message) {
    messageRef.current = message;
  }

  return (
    <ToastContainer onClose={onClose} show={!!message} delay={7000} animation transition={transition}>
      <ToastHead>
        <strong className="mr-auto">{messageRef.current.head}</strong>
        <small>{messageRef.current?.detail}</small>
      </ToastHead>
      <ToastBody>{messageRef.current.body}</ToastBody>
    </ToastContainer>
  );
};

Question1: How can I define transition?

Question2: How can I write the transition inside JSX?

Any suggestions would be helpful! Thank you!!


Solution

  • You can get the typescript definition by including

    import {TransitionComponent} from "react-bootstrap";
    

    To use a transition, it looks like you import a TransitionComponent either from react-bootstrap, which includes Collapse and Fade, or from the underlying package react-transition-group. You pass the whole component to ToastContainer. If a transition prop is not included, it defaults to Fade.

    import {Collapse, Toast as ToastContainer} from "react-bootstrap";
    
    <ToastContainer onClose={onClose} show={!!message} delay={7000} animation transition={Collapse}>