Tips on customizing Chakra UI toast notifications with specific colors using chakra-ui/react 2.4.2 and next.js v13

I'm currently exploring ways to incorporate color and background styles into my Chakra UI toast component.

Below is a sample code snippet of my custom toast component:

import type { UseToastOptions } from "@chakra-ui/react"
import { useToast as useChakraToast } from "@chakra-ui/react"

export function useToast() {
  const toast = useChakraToast()
  const handleToast = (props: UseToastOptions) => {
    toast({
      position: "bottom-right",
      isClosable: true,
      status: "success",

      ...props,
    })
  }
  return handleToast
}

Although the toast functionality works, I am struggling to apply color styles to it. Here's an example where I attempt to use the toast:

import { useApolloClient } from "@apollo/client"
import { useRouter } from "next/router"

import { useToast } from "./useToast"

export const useLogout = () => {
  const client = useApolloClient()
  const router = useRouter()
  const toast = useToast()
  const handleLogout = async () => {
    await router.replace("/logout")
    await fetch("/api/logout", { method: "post" })
    await client.resetStore()
    toast({ description: "Successfully logged out!" } )
  }
  return handleLogout
}

I am looking for a way to define success with color: "brand.white" and bg: "brand.green" in the useToast component. However, these values are not being accepted. I have also tried adding them in the logout toast without success.

Where should I specify these color properties?

I attempted to add properties to my theme.tsx file as follows:

... ... ...

Module '"@chakra-ui/react"' has no exported member 'createMultiStyleConfigHelpers'

I am currently using version "2.4.2" of "@chakra-ui/react", and I am unable to implement the method described in the Chakra UI documentation.

Next step:

I came across this post discussing issues with next v13. After trying versions 2.4.4 and 2.4.2, I settled for 2.4.2 due to compatibility concerns with 2.4.4.

In an attempt to customize alert styles, I created an alert.ts file with shades of green for success and red for error, defined as brand colors in my extendTheme:

... ... ...

Despite these efforts, when using this custom styling in my toast, I consistently get a white background with black text. The appearance remains unchanged regardless of success or failure.

Is it possible for Chakra to utilize brand colors in alerts?

The useToastOptions.ts file contains:

... ... ...

Answer №1

Per the Chakra UI documentation, a common approach would involve creating custom variants for the Alert component, which is internally used by Toast. This allows for styling of Toast using these predefined variants.

In a fresh install of Chakra UI with a basic configuration, importing the createMultiStyleConfigHelpers does not yield any noticeable errors during testing.

For a straightforward live demonstration of this concept, check out this example on: stackblitz.

To begin, define styles for the custom variants within the theme:

// You may need to install '@chakra-ui/anatomy'

import { alertAnatomy } from '@chakra-ui/anatomy';
import {
  ChakraProvider,
  extendTheme,
  createMultiStyleConfigHelpers,
} from '@chakra-ui/react';

const { definePartsStyle, defineMultiStyleConfig } =
  createMultiStyleConfigHelpers(alertAnatomy.keys);

// 👇 Defining styles for the first custom variant
const customSuccess = definePartsStyle({
  container: {
    border: '1px solid',
    borderColor: 'teal.200',
    background: 'teal.500',
    _dark: {
      borderColor: 'teal.600',
      background: 'teal.800',
    },
  },
  title: {
    color: 'pink.200',
    _dark: {
      color: 'pink.200',
    },
  },
});

// 👇 Defining styles for the second custom variant
const customError = definePartsStyle({
  container: {
    border: '1px solid',
    borderColor: 'pink.200',
    background: 'pink.400',
    _dark: {
      borderColor: 'pink.600',
      background: 'pink.800',
    },
  },
  title: {
    color: 'teal.200',
    _dark: {
      color: 'teal.300',
    },
  },
});

const alertTheme = defineMultiStyleConfig({
  variants: { customSuccess, customError },
});

export const theme = extendTheme({
  components: {
    Alert: alertTheme,
  },
});

Then, apply these styles to the useToast function where its variant property references the same variants set for the Alert component:

<Button
  colorScheme="teal"
  onClick={() =>
    toast({
      title: "Account created.",
      description: "We've created your account for you.",
      status: "success",
      duration: 9000,
      isClosable: true,
      variant: "customSuccess",
    })
  }
>
  Show success
</Button>
<Button
  colorScheme="pink"
  onClick={() =>
    toast({
      title: "Account created.",
      description: "We've created your account for you.",
      status: "error",
      duration: 9000,
      isClosable: true,
      variant: "customError",
    })
  }
>
  Show error
</Button>

Answer №2

Struggling with customizing the appearance of the Alert component? I faced a similar issue and was able to solve it through some experimentation. By adjusting the component styles within my theme.js file, I achieved the desired look:

//_app.js
import { theme } from 'theme';

<ChakraProvider theme={theme}>
//... 
</ChakraProvider >

//theme.js

import { extendTheme } from '@chakra-ui/react';

const textStyles = {...}
const colors = {...}

const components = {
  Alert: {
    variants: {
      solid: {
        container: {
          bg: '#fff',
          ...
        },
        title: {
          color: 'brand',
        },
        description: {
          ...
        },
        icon: {
          ...
        },
      },
    },
  },
};

export const theme = extendTheme({ colors, components, textStyles });

Answer №3

Using a custom toast in chakra-ui can enhance the functionality.

const notification = useToast()

notification({
      duration: 5000,
      isClosable: true,
      render: () => (
        <CustomNotification
          description="Your Message"
          status="error" // Choose between "success", "info", or "error"
        />
      ),
    })

The custom toast component may utilize the Alert component from chakra.

<Alert status={status}> {description} </Alert>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Effortlessly switching classes in JavaScript for seamless transitions

I'm currently working on an animation project where I want the title to be visible on the page initially, and then slowly fade away as you scroll down, with a subtitle fading in right after. While I've managed to get the title part working, I&apo ...

Creating PDFs using Puppeteer in the presence of `link` tags

On my website, students have the ability to create their own notes using a RichText editor where the content can be quite complex. I want to provide them with an option to download these notes as a PDF file. To achieve this, I am planning to use the "puppe ...

Creating an undo feature for a dynamically generated checklist of checkboxes

I am using a combination of javascript/jquery and html to dynamically populate the page with checkboxes. When you click "add", a new checkbox is created. I am now looking for a way to add an undo button that would delete the last checkbox created. Here is ...

Fluid imitation pillars with a decorative outer edge

Looking to create a modern, sleek 2-column HTML5 interface with a left sidebar and main content area on the right. Backwards compatibility is not an issue as all users will be using the latest versions of Chrome or FF. The goal is to give the sidebar a ba ...

The issue experienced in next-auth is due to a TypeError where the function res.getHeader is not

Currently, my focus is on the next 13 along with utilizing the next-auth. I've encountered an error stating TypeError: res.getHeader is not a function while validating the API by using getServerSession(req, res, authOptions) to determine if the user i ...

Ways to position an element at the edge of the browser either on the left or right side when the image is not in a centered container

Looking to create a unique layout that involves: Utilizing a three-column structure Incorporating a div element that spans two columns Positioning an image within the two-column div so that it extends to the left edge of the browser window while staying ...

Getting the ID of an element in ReactJS following a POST request

I am looking to implement a function that creates an entry in a database using data collected from a basic form. Once the user clicks on submit, this function is triggered: createItem(item){ this.state.bucket_list.push({ name: item, ...

Enhance your checkbox and radio components with React Higher Order Components (H

I'm in the process of designing my own custom checkbox and radio components to ensure reusability. This is what I have so far: import React, { Component } from 'react' export class Checkbox extends Component { render() { return ...

Header text refuses to cooperate and center itself

Struggling to find the best way to center the "Header" text while keeping the icon in place. I've tried using text-align: center;, but it's not producing the desired results. Could anyone provide guidance on how to achieve this? Thanks. IMG: ...

Preventing a timer from pausing in NextJS during periods of inactivity

Recently, I developed a straightforward timer application using Next.js that should continue counting even when the browser window is inactive. However, I noticed that if I switch to another window for approximately 5 minutes, the timer stops counting whi ...

404 Error: The POST Route for Express, React, and Node.js Cannot Be Located

I encountered an issue while trying to upload a file through a post request, resulting in the following error: POST http://localhost:8080/api/files 404 (Not found). The URL of the page I'm attempting to upload the file from is http://localhost:808 ...

Issues with hover functionality in Javascript, CSS, and HTML

Seeking assistance with my JavaScript, HTML, and CSS development, I ran into an issue while trying to create a hovering function for my webpage. Despite my efforts, the links are not displaying anything when hovered over, and the divs meant for specific ho ...

Ways of incorporating text in a parallelogram shape

Here is the HTML code with ID attributes applied to both divs: <div id="herotext"> <div id="banner"></div> <h1 id="maintitle">Hey, I'm Charlie</h1> <p>This websi ...

Steps for changing an image with another image upon button click in Angular 6

I have a button with an image and text. When the button is clicked, I want to change both the image and content. Here's the code I'm currently using: <div class="btn-default"> <button name="Save" [ngClass]="[bntStyle]" (click)="submit ...

Error with Display of ASCII Character 62 in Superfish Menu

Currently, I have implemented the Superfish menu on my website. In order to indicate sub-menus within my menus, I have opted to utilize the character entity code &#62;, which historically has represented ">". Oddly enough, while viewing my website ...

Incorporating React.js into HTML DOM Elements

As a beginner in react js, I'm facing an issue regarding DOM elements. Within my component, there is a table. When hovering over a cell, I want to highlight both the corresponding row and cell. Additionally, I need to obtain the coordinates of the hov ...

Create a React form that dynamically generates fields based on the serializer configuration in Django Rest Framework

In my quest to develop a web application for users to post various ads for sale - ranging from cars to apartments and gadgets - I've found that each category in the Django models requires specific fields in the form for creating an ad. Fortunately, cr ...

Tips on expanding the background beyond the boundaries of a parent container with a specific width limit

Could you please take a look at the code snippet below? I am dealing with a situation where I have a container with a fixed width, and inside that container, there are rows whose width exceeds that of the parent container. Some of these rows have a backgro ...

tips for moving a button 2 pixels up or down in position

How can I adjust the position of my button by a specific number of pixels up or down from where it currently is? Can you provide guidance on how to find the current location? Thank you in advance. ...

Encountered an error with create-react-app and MaterialUI: Invalid hook call issue

I am encountering an issue while trying to set up Create-react-app with Material UI. The error message I receive pertains to Hooks. Could there be something else that I am missing? This is the specific error message being displayed: Error: Invalid hook ...