Dynamically create react-bootstrap toasts via a simple api.

Overview

React-Bootstrap-Toasts

Dynamically create react-bootstrap toasts via a simple api.

Live demo

building...

Installation

# npm
npm install react-bootstrap-toasts

# yarn
yarn add react-bootstrap-toasts

# pnpm
pnpm add react-bootstrap-toasts

Basic Usage

1: Wrap your app inside a ToastsProvider component:

import { ToastsProvider as BootstrapToastsProvider } from 'react-bootstrap-toasts';

<BootstrapToastsProvider>
  <App />
</BootstrapToastsProvider>;

2: Use useToasts hook:

import { Button } from 'react-bootstrap';
import { useToasts } from 'react-bootstrap-toasts';

function App() {
  const toasts = useToasts();

  return (
    <Button
      onClick={() => {
        toasts.show({
          headerContent: 'Bootstrap',
          bodyContent: 'Toast body content.',
          toastProps: {
            bg: 'primary',
          },
        });
      }}
    >
      Show toast
    </Button>
  );
}

Toast Options

toasts.show method accepts a toastOptions argument to control behavior of the created toast. Here is toastOptions type definition:

type ToastOptions<T extends ToastProps> = {
  headerContent: string | JSX.Element;
  bodyContent: string | JSX.Element;
  toastProps?: T;
  toastHeaderProps?: ToastHeaderProps;
  toastBodyProps?: BsPrefixProps & HTMLAttributes<ElementType>;
};

headerContent: Child elements of react-bootstrap Toast.Header component.

bodyContent: Child elements of react-bootstrap Toast.Body component.

toastProps: A ToastProps object which will be passed down to react-bootstrap Toast component.

toastHeaderProps: A ToastHeaderProps object which will be passed down to react-bootstrap Toast.Header component.

toastBodyProps: A object which will be passed down to react-bootstrap Toast.Body component.

For example, to create an autohide toast with contextual danger variation:

import { Button } from 'react-bootstrap';
import { useToasts } from 'react-bootstrap-toasts';

function App() {
  const toasts = useToasts();

  return (
    <Button
      onClick={() => {
        toasts.show({
          headerContent: <span className="me-auto">Bootstrap</span>,
          bodyContent: 'Toast body content.',
          toastProps: {
            bg: 'danger',
            autohide: true,
            delay: 3000,
          },
        });
      }}
    >
      Show toast
    </Button>
  );
}

For more details, please check react-bootstrap toasts API.

Toast Container Props

ToastsProvider accepts a toastContainerProps prop, which is a ToastContainerProps object that will be passed down to react-boostrap ToastContainer component.

Usually you want this to control the position where toasts to place or apply additional css style to the toast container.

The example below shows how to set all toasts should be placed at top-end of the viewport and also set the toast container's padding:

import { ToastsProvider as BootstrapToastsProvider } from 'react-bootstrap-toasts';

<BootstrapToastsProvider toastContainerProps={{ position: 'top-end', className: 'p-2' }}>
  <App />
</BootstrapToastsProvider>;

Hide Toast

The toasts.show method returns an id of the created toast which can be used to hide the toast manually via toasts.hide method:

import { useState } from 'react';
import { Button } from 'react-bootstrap';
import type { ToastIdType } from 'react-bootstrap-toasts';
import { useToasts } from 'react-bootstrap-toasts';

function App() {
  const toasts = useToasts();
  const [toastId, setToastId] = useState<ToastIdType | undefined>();
  {
    toastId === undefined ? (
      <Button
        className="me-3"
        onClick={() => {
          const id = toasts.show({
            headerContent: <span className="me-auto">Bootstrap</span>,
            bodyContent: 'Toast body content.',
          });
          setToastId(id);
        }}
      >
        Show toast
      </Button>
    ) : (
      <Button
        variant="danger"
        onClick={() => {
          toasts.hide(toastId);
          setToastId(undefined);
        }}
      >
        Hide toast
      </Button>
    );
  }
}

Shotcut methods

react-bootstrap provides some contextual variations of toasts. react-bootstrap-toasts provides a corresponding shortcut method for each contextual variation. For example:

const toasts = useToasts();

// create a contextual warning toast
toasts.warning({
  headerContent: <span className="me-auto">Bootstrap</span>,
  bodyContent: 'Toast body content.',
});

// is equivalent to
toasts.show({
  headerContent: <span className="me-auto">Bootstrap</span>,
  bodyContent: 'Toast body content.',
  toastBodyProps: {
    bg: 'warning',
  },
});

All available shortcut methods:

toasts.info(toastOptions: ToastOptions<ToastPropsOmitBg>): ToastIdType;

toasts.primary(toastOptions: ToastOptions<ToastPropsOmitBg>): ToastIdType;

toasts.secondary(toastOptions: ToastOptions<ToastPropsOmitBg>): ToastIdType;

toasts.success(toastOptions: ToastOptions<ToastPropsOmitBg>): ToastIdType;

toasts.danger(toastOptions: ToastOptions<ToastPropsOmitBg>): ToastIdType;

toasts.warning(toastOptions: ToastOptions<ToastPropsOmitBg>): ToastIdType;

toasts.dark(toastOptions: ToastOptions<ToastPropsOmitBg>): ToastIdType;

toasts.light(toastOptions: ToastOptions<ToastPropsOmitBg>): ToastIdType;

TODO

  • Improving documentation.
  • Smoother animation of toast transition.
You might also like...
React-Login-app - Create a Login and Registration Page with React Router
React-Login-app - Create a Login and Registration Page with React Router

About In this repo I was given a Task to create a Login and Registration page wh

Aviasales React-Redux-MobX- - A quick start Redux + TypeScript Create React App template

A quick start Redux + TypeScript Create React App template An opinionated quick

📑 A React component to easily create demos of other components
📑 A React component to easily create demos of other components

React DemoTab 📑 A React component to easily create demos of other components Install npm install react-demo-tab Demo DemoTab example Example import R

JSONX - Create React Elements, JSX and HTML from JSON

JSONX Description JSONX is a module that creates React Elements, JSX and HTML from JSON. Declarative The JSONX UMD comes with batteries included so yo

Easily download Figma and create SVGs components for Vue, React, Angular and more to come

Easily download Figma and create SVGs components for Vue, React, Angular.

The goal of this exercise is to create a demo calendar application using React

The goal of this exercise is to create a demo calendar application using React. We strongly recommend create-react-app to make the bootstrapping of your application really easy.

:speech_balloon: Easy way to create conversation chats
:speech_balloon: Easy way to create conversation chats

React Simple Chatbot A simple chatbot component to create conversation chats Getting Start npm install react-simple-chatbot --save Usage There are sev

Create guided tours in your apps
Create guided tours in your apps

React Joyride Create awesome tours for your app! Showcase your app to new users or explain functionality of new features. It uses react-floater for po

Youtube Tutorial showcasing how to create a fullstack NFT mingint dapp.
Youtube Tutorial showcasing how to create a fullstack NFT mingint dapp.

Emoji Faces NFT Minting dApp This a complete example of fullstack NFT minting dApp. EmojiFaces is built with the purpose of providing an entry point f

Owner
jukanntenn
jukanntenn
Dynamically classnames in React.

Reclsx Dynamically classnames in React Based on react/jsx-runtime Using classNames/dedupe Example import React from 'react'

Daniel 6 Oct 27, 2022
Uses TypeScript and Proxy to dynamically construct a lens-like interface for your application state.

Lenses in React Uses TypeScript and Proxy to dynamically construct a lens-like interface for your application state. Example You can construct a lens/

Gabe Scholz 13 Feb 24, 2022
Quickly load Vue, React, SpriteJS components via command line

Faster way to render & interact react & vue3 components with command line interface.

稀土 6 Mar 9, 2022
Execute Power FX in your client (React) via .NET (WASM) and JS interop.

WIP, details TBD Click here for live DEMO. Based on: https://github.com/microsoft/power-fx-host-samples/tree/main/Samples/WebDemo Blog post: https://h

NETWORG 10 Nov 16, 2022
React project with Google Firebase API, create partys with admin view and user view. Users can ask topics to admin, and support other topics.

?? Tecnologias Esse projeto foi desenvolvido com as seguintes tecnologias: React Firebase TypeScript ?? Como executar Clone o projeto e acesse a pasta

Felipe Souza 3 Aug 27, 2021
React Query Typed Api - An opinioneted wrapper around react-query to implement fully typed api requests

React Query Typed Api - An opinioneted wrapper around react-query to implement fully typed api requests

Apperside 5 Aug 5, 2022
Simple react native app to fetch and list contacts from an API

Contact list Simple react native app to fetch and list contacts from an API, and show each contact detail in a modal Can't wait to test, don't worry c

João Amadeu 2 Jul 11, 2022
A very simple wrapper of pinia to try difference API

pinia-dx Pinia DX improvement experiment (Composition API Only). This is a very simple wrapper of pinia to try difference API. import { reactive, toRe

Johnson Chu 3 Oct 27, 2021
Settings - Simple settings module for kernel with an API out of the box

Kernel Settings Simple settings module for kernel with an API out of the box. In

null 7 Aug 2, 2022
A drum machine built with React using the Create React App toolchain.

drum-machine A simple drum machine built with React using the Create React App toolchain. Getting Started Clone or download the repository. Open a com

Ryan Schafer 1 Dec 30, 2021