Material ui error message

Snackbars provide brief messages about app processes. The component is also known as a toast.

Snackbars provide brief messages about app processes. The component is also known as a toast.

Snackbars inform users of a process that an app has performed or will perform. Они времени отображаются в нижней части экрана (данное поведение можно изменить). They shouldn’t interrupt the user experience, and they don’t require user input to disappear.

Всплывающие компоненты содержат одну строку текста, непосредственно связанную с выполненной операцией. Они могут содержать текстовое действие, но не иконки. Вы можете использовать их для отображения уведомлений.

  • Обратная связь
  • WAI-ARIA
  • Размер пакета
  • Material Design
  • Figma
  • Adobe
  • Sketch

Количество на странице

В один момент на странице можно отобразить только один всплывающий компонент.

Простые всплывающие компоненты

A basic snackbar that aims to reproduce Google Keep’s snackbar behavior.

<Button onClick={handleClick}>Open simple snackbar</Button>
<Snackbar
  open={open}
  autoHideDuration={6000}
  onClose={handleClose}
  message="Note archived"
  action={action}
/>

Customized snackbars

Ниже находятся примеры кастомизации компонента. You can learn more about this in the overrides documentation page.

<Button variant="outlined" onClick={handleClick}>
  Open success snackbar
</Button>
<Snackbar open={open} autoHideDuration={6000} onClose={handleClose}>
  <Alert onClose={handleClose} severity="success" sx={{ width: '100%' }}>
    This is a success message!
  </Alert>
</Snackbar>
<Alert severity="error">This is an error message!</Alert>
<Alert severity="warning">This is a warning message!</Alert>
<Alert severity="info">This is an information message!</Alert>
<Alert severity="success">This is a success message!</Alert>

Позиционированные всплывающие уведомления

In wide layouts, snackbars can be left-aligned or center-aligned if they are consistently placed on the same spot at the bottom of the screen, however there may be circumstances where the placement of the snackbar needs to be more flexible. You can control the position of the snackbar by specifying the anchorOrigin prop.

{buttons}
<Snackbar
  anchorOrigin={{ vertical, horizontal }}
  open={open}
  onClose={handleClose}
  message="I love snacks"
  key={vertical + horizontal}
/>

Длина сообщения

Some snackbars with varying message length.

Переходы

Consecutive Snackbars

When multiple snackbar updates are necessary, they should appear one at a time.

Snackbars and floating action buttons (FABs)

Snackbars should appear above FABs (on mobile).

Изменение анимации

Увеличение — это анимация, которая используется по умолчанию, но вы можете использовать другую анимацию.

<Button onClick={handleClick(GrowTransition)}>Grow Transition</Button>
<Button onClick={handleClick(Fade)}>Fade Transition</Button>
<Button onClick={handleClick(SlideTransition)}>Slide Transition</Button>
<Snackbar
  open={state.open}
  onClose={handleClose}
  TransitionComponent={state.Transition}
  message="I love snacks"
  key={state.Transition.name}
/>

Control Slide direction

Вы можете изменить направление анимации.

<Button onClick={handleClick(TransitionLeft)}>Right</Button>
<Button onClick={handleClick(TransitionUp)}>Up</Button>
<Button onClick={handleClick(TransitionRight)}>Left</Button>
<Button onClick={handleClick(TransitionDown)}>Down</Button>
<Snackbar
  open={open}
  onClose={handleClose}
  TransitionComponent={transition}
  message="I love snacks"
  key={transition ? transition.name : ''}
/>

Дополнительные проекты

Для более сложных вариантов использования вы можете воспользоваться:

notistack

stars npm downloads

This example demonstrates how to use notistack. notistack has an imperative API that makes it easy to display snackbars, without having to handle their open/close state. It also enables you to stack them on top of one another (although this is discouraged by the Material Design specification).

Доступность

(WAI-ARIA: https://www.w3.org/TR/wai-aria-1.1/#alert)

  • По умолчанию всплывающий компонент не будет скрываться автоматически. Однако, если вы решите использовать функцию autoHideDuration, рекомендуется дать пользователю достаточное время для реагирования.

Next, open up the App.js file located in the src folder. You should see this:

App.js

import React from 'react'; import TextField from '@mui/material/TextField'; import './App.css'; import { Button, Radio, RadioGroup, FormControlLabel, FormControl, FormLabel, FormHelperText, FormGroup, Checkbox, } from '@mui/material'; import { useForm } from "react-hook-form"; const App = () => { const { register, handleSubmit, watch, formState: { errors } } = useForm(); const onSubmit = (data) => console.log(data); console.log(errors); return ( <div className="App__form"> <h1> Material UI with React Hook Form - Validation with Error Messages </h1> <form onSubmit={handleSubmit(onSubmit)}> <TextField id="outlined-basic" name="firstName" label="First Name" variant="outlined" fullWidth {...register("firstName", { required: "First Name is required." })} error={Boolean(errors.firstName)} helperText={errors.firstName?.message} /> <TextField id="outlined-basic" label="Last Name" variant="outlined" fullWidth name="lastName" {...register("lastName", { required: "Last Name is required." })} error={Boolean(errors.lastName)} helperText={errors.lastName?.message} /> <TextField id="outlined-basic" label="E-mail" variant="outlined" fullWidth name="email" {...register("email", { required: "E-mail Address is required." })} error={Boolean(errors.email)} helperText={errors.email?.message} /> {/* Radio button */} <FormControl error={Boolean(errors.gender)} > <FormLabel component="legend"> Choose Your Gender </FormLabel> <RadioGroup row aria-label="gender" name="gender"> <FormControlLabel value="female" control={ <Radio {...register("gender", { required: "Choose your gender" })} /> } label="Female" /> <FormControlLabel value="male" control={ <Radio {...register("gender", { required: "Choose your gender" })} /> } label="Male" /> <FormControlLabel value="other" control={ <Radio {...register("gender", { required: "Choose your gender" })} /> } label="Other" /> </RadioGroup> <FormHelperText style={{color:'#d32f2f'}}>{errors.gender?.message}</FormHelperText> </FormControl> <div className="clearfix"></div> {/* Check box */} <FormGroup error={Boolean(errors.tnc)} style={{ display: "block", marginTop: "17px" }} > <FormControlLabel control={ <Checkbox name="tnc" {...register("tnc", { required: "please aggre our terms and condtions" })} /> } label="I aggree all terms and conditions" /> </FormGroup> <FormHelperText style={{color:'#d32f2f'}}>{errors.tnc?.message}</FormHelperText> <div className="clearfix"></div> <Button variant="contained" color="primary" type="submit" className="btns"> create new account </Button> </form> </div> ) } export default App

The MUI Snackbar component (also known as a Toast message) provides a simple way to notify users about important information. The component can be quickly styled and has several handy props for customizing transitions. In this post we will create an example Snackbar and I will explain the props I use.

A common third-party library used with Snackbar is Notistack, which controls queueing of Snackbars.

There is a Code Sandbox link with a live demo in the Resources section.

Material-UI Snackbar Content

The Snackbar component has one support component called SnackbarContent. Interestingly, the DOM renders the same whether you use the component or not.

In the screenshot below, we see a div with class .MuiSnackbarContent-root. This renders the same when you use either code snippet below:

//method 1
<Snackbar message="Cool styling!"/>

//method 2
<Snackbar>
  <SnackbarContent message="Cool styling!"/>
</Snackbar>
MUI SnackbarContent in the DOM

Since both methods are the same, I suggest you use the one that requires less code.

It’s also important to notice that you need to use the message prop instead of passing text as a child component of the Snackbar.

Material-UI Snackbar with Line Break

The MUI Snackbar is not intended to have a multiline message (but there is a backdoor way to do it). Here’s what the docs say:

Snackbars contain a single line of text directly related to the operation performed,

MUI Snackbar Docs

I tried several methods for adding a line break, and the Snackbar ignored all of them. For example, passing <br/> and r as part of the message prop did not work.

What did work is passing an Alert component as child of Snackbar:

<Snackbar>
  <Alert severity="success" sx={{ width: "100%" }}>
    This is a success message! <br />
    Test Successful
  </Alert>
</Snackbar>

Here the line break is respected.

Material-UI Snackbar Size and Style

The MUI Snackbar has responsive styling by default:

  • If the viewport is less than 600px, the Snackbar will take full width
  • If the viewport is greater than 600px, the Snackbar will take up a maximum width of 240px

Take a look at the DOM screenshot below. Interestingly, the media query uses left: 'auto' to accomplish the sizing of 240px.

Width can easily be customized by adding a width attribute to the sx prop. It will affect the Snackbar at all breakpoints.

Other stylings can be applied with the sx prop as well. Remember how we discussed the SnackbarContent prop above? Some stylings require a nested selector targeting .MuiSnackbarContent-root in order to properly take effect.

Here’s the styling code for width, color, and background color:

<Snackbar
  sx={{
    width: 400,
    color: "secondary",
    //backgroundColor: "green", This doesn't work
    "& .MuiSnackbarContent-root": { backgroundColor: "green" }
  }}
/>

Color and width are applied at the root level, but the background color has to be applied to the child element in the DOM. Play around with it in the Code Sandbox and learn more.

Material-UI Snackbar Slide and Transition

There are lots of customizations available for Snackbar transitions. I set the below props in my demo:

anchorOrigin={{ vertical: "top", horizontal: "right" }}
autoHideDuration={1000}
transitionDuration={{ enter: 1000, exit: 2000 }}
TransitionComponent={Slide}

TransitionProps={{ enter: true, exit: false}}
  • anchorOrigin – this controls where the Snackbar appears
  • autoHideDuration – this control if and when the Snackbar closes itself. This will automatically fire the close event
  • transitionDuration – the amount of time it take appearance, enter, and exit transitions to complete. In my example I omitted the appear field
  • TransitionComponent – There are three different component options: Slide, Grow, and Fade
  • TransitionProps – This is a “prop of props”. It passes props to the underlying Transition object. I simply used it to disable the exit transition

MUI makes transitions easy with its assortment of props. Be aware that a transition is itself a component that accepts props.

Resources

My MUI course on Udemy is now available!!! Build a full MUI app from beginning to end, learn every aspect of the sx prop, styled API, and the theme, and tackle the most challenging components! Do you want an active Q&A with me?!? Check here for coupons for my MUI course on Udemy.

The MUI Dialog component has a similar use case to the Snackbar.

Code Sandbox Link

MUI Snackbar API docs

MUI SnackbarContent API docs

Понравилась статья? Поделить с друзьями:
  • Matcompas dll error 193
  • Matchescounterror ведьмак 3 как исправить
  • Matches count error the witcher 3
  • Matcher error received value must be a mock or spy function
  • Match domain error