Is there a way to customize the styles for the material UI alert component?

My journey with Typescript is relatively new, and I've recently built a snackbar component using React Context. However, when attempting to set the Alert severity, I encountered this error: "Type 'string' is not assignable to type 'Color | undefined'." Even though I have specified the type as string, I'm struggling to assign it a type of Color. Below is my Alert component code:

const AppAlert = () => {
  const alertContext = useContext(AlertContext);

  return (
    <div>
      <Snackbar open={alertContext.snackbarOpen}>
        <Alert severity={alertContext.snackbarType} variant="filled">
          {alertContext.snackbarMessage}
        </Alert>
      </Snackbar>
    </div>
  );
};

export default AppAlert;

Take a look at my Alert prop types below:

interface AlertProps {
  snackbarOpen: boolean;
  snackbarType: string;
  snackbarMessage: string;
  setAlert: (type: string, message: string) => void;
}

I hope my explanation was clear enough. I am still on the path to understanding TypeScript.

Answer №1

Material-ui alerts have four potential severity types:

'error' | 'info' | 'success' | 'warning'
, as outlined in the documentation found at this link: material-ui.com/api/alert. The issue you're facing is due to the severity property of your Alert component being set to an undefined value from alertContext.snackbarType. To prevent errors in case of any mishaps, it's best practice to define a default severity type like so:

<Alert severity={alertContext?.snackbarType || 'warning'} variant="filled">
    {alertContext?.snackbarMessage}
</Alert>

Answer №2

Dealing with a similar issue recently, I managed to resolve it by importing the type from @material-ui/lab/Alert:

import React from 'react';
import Alert from '@material-ui/lab/Alert';
import type { Color } from '@material-ui/lab/Alert'

interface Props{
    severity: Color,
    message: string
}

export const BuildReportAlert = (props: Props) => {

    const {severity, message} = props;

    return (
        <Alert
            variant='outlined'
            severity={severity}
        >
            {message}
        </Alert>
    )

}

Answer №3

To manage alerts in React, you can utilize the useState hook to create an object that stores severity and message information.

const [alertInfo, setAlertInfo] = useState({
    severity: "warning",
    message: "This is a warning alert — pay attention!",
  }); 

Here is an example of how to use this object with a Mui component:

<Alert severity={alertInfo.severity}>{alertInfo.message}</Alert>

This setup allows you to easily update the severity and message content as needed.

Answer №4

Attempting the same approach, I encountered an error message:

Type 'string' cannot be assigned to type 'OverridableStringUnion<AlertColor, AlertPropsColorOverrides> | undefined'.ts(2322)
Alert.d.ts(85, 3): The expected type is from the property 'severity' declared in the type 'IntrinsicAttributes & AlertProps & AlertSlotsAndSlotProps'
(property) AlertProps.severity?: OverridableStringUnion<AlertColor, AlertPropsColorOverrides> | undefined

In my setup, I configured my alert to accept a message and "severity" based on success or failure...

const [alertText, setAlertText] = useState({
      'severity': 'success',
      'text': ''
    })

Priorly, I had:

{alertText && <Alert id={alertText.severity} severity={alertText.severity}>{alertText.text}
        </Alert>}

I experimented with replacing sx={{ severity: ${alertText.severity} }} and it alleviated the issue!

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

Ways to customize the border of the ListItemButton when it's in a selected state using Material UI?

I'm currently working on a feature that involves highlighting a ListItemButton with a specific background color when selected. However, I now want to take it a step further and add an outline or border color around the ListItemButton when it is select ...

What is the reason behind the array.map() function not altering the original array?

I attempted to increment each element of my array by one, but was having trouble. Here is what I tried: myArray=[1,2,3] myArray.map(a=>a+=1) // also tried a++ and a=a+1 console.log(myArray) // returns [ 1 , 2 , 3 ] Unfortunately, this method did not w ...

On the second attempt to call setState within the componentDidMount method, it is not functioning as expected

As a newcomer, I am delving into the creation of a memory game. The main objective is to fetch data from an API and filter it to only include items with image links. On level one of the game, the task is to display three random images from the fetched data ...

The functionality of Express' render/redirect is limited to being triggered only by a submit method within a form

Objective To execute a POST request through a JavaScript method in order to send variable values as parameters. Setup NodeJS Express BodyParser ejs Initial Approach Frontend: <html> <head> <script src='http://ajax.go ...

Using Javascript or Jquery, you can submit a form without the need for a button

I'm attempting to submit a form without using a button by invoking a JavaScript function and processing the form with JQUERY/PHP. My goal is for the form to be submitted silently on the backend without causing the page to reload. However, I keep encou ...

What is the most effective method for applying numerous textures or images to a single Sphere in three.js?

Just like the title says, I'm attempting to create a similar setup to what's showcased on this website: I have the images handy, but I'm currently figuring out how to arrange them all onto a single sphere. Appreciate any guidance you can o ...

What is the process for generating a collection of objects in a Mongoose Model?

I am currently working on creating a structure similar to this: var User = mongoose.model('Clicker', totalClicks: [ {type: Number, default: 0}, {type: Number, default: 0} ], I have explored various documentation resources related to ...

Executing an Amplifyjs GET request containing a request body

Is it possible to utilize GET requests with a message body using AmplifyJS? Specifically, I am curious about the process of achieving this functionality with AmplifyJS. While synthetic tests function properly (using Fiddler as my test client), I have enc ...

Looking to crop a canvas without changing its dimensions using jQuery

I'm currently working on a project that involves overlaying two images; one uploaded by the user and the other a default image. However, I am facing an issue when the uploaded image is a rectangle instead of a square, causing the canvas to resize it. ...

The beforeRouteEnter callback function fails to trigger

I'm encountering an issue with my simple routes: /follower/:token/edit and /follower/new Whenever I navigate from the first route to the second one using $router.push('/follower/new'), the beforeRouteEnter hook is triggered, but the callbac ...

Bring in numerous variables into a Gatsby component using TypeScript and GraphQL Typegen

import { graphql } from 'gatsby'; const Footer = ({phone}: { phone?: Queries.FooterFragment['phone'];}): JSX.Element => { return <footer>{phone}</footer>; }; export default Footer export const query = graphql` fragm ...

Can you customize the buttons in the operation panel of an antd image preview window?

I am looking to add a button that allows users to download or share the image being previewed. Is there a way to achieve this functionality? I have researched and read through the documentation but have not found a solution yet. ...

Angular: Error when TypeScript object returns an array object value

I have encountered a strange issue where the array value returned as [object Set] when I console log it. It's unclear whether this problem is occurring in the component or the service, but the object values are not being displayed. This issue arises ...

What is the reason for being unable to remove the event listener from a sibling element?

function show1() { console.log("ok1"); document.getElementById("a2").removeEventListener("click", delegate); } function show2() { console.log("ok2"); } function show3() { console.log("ok3"); } function delegate(event) { var flag = event.target ...

The width of my root container does not display at a full 100% in mobile dimensions

After creating a simple React.js project, I set up the folder structure using `npx create-react-app`. Additionally, I added some styling with `* { margin: 0; padding: 0; box-sizing: border-box }`, and specified background colors for the body and #root elem ...

How to Target a Specific Element Using its Class with jQuery

Hey there! I'm currently working with the following snippet of HTML code: <li class="grey"> <div class="row"> <button id="test" style="width:50%;" class="btn btn-blue-white cartBtn">Add to Cart</button> </div ...

Using Selenium WebDriver and JavaScript: Enabling Chrome to Download Multiple Files at Once

After scouring through multiple documents for hours like https://www.selenium.dev/documentation/en/webdriver/js_alerts_prompts_and_confirmations/ as well as https://chromedriver.chromium.org/capabilities and I was unsuccessful in finding a solution wit ...

Having trouble with Onsen UI + React Navigator pushPage function?

After experimenting with the Onsen playground and React Combining Navigator and Tabbar example, I created this unique animation: I decided to reposition the button and input field for adding more users by using a fab. However, when I attempted to call nav ...

Exploring the process of sending JSON responses through Express

I recently started working with node/express. My express app has a single post route ('/'), which is designed to retrieve information about GitHub users based on their usernames. For instance, when I make a post request like this { "develop ...

"Bootstrap-Wizard: How to troubleshoot the onPrevious function not working when used with an

I have been incorporating a bootstrap wizard into one of my applications, and I have encountered an issue. When attempting to utilize the index position of the tabs to achieve a specific goal, I found that it only works with the next button and not with th ...