• notice
  • Congratulations on the launch of the Sought Tech site

How to display SnackBarMaterialUI in if statement

If my camera component returns some errors, I want to show a snackbar notification.I tried putting the component in a function and passing the error message as a prop and calling it in the if statement but it didn't work.I've also tried echoing the snack bar itself, which doesn't show up either, and console.log or alert messages work fine either way.I'm not showing some parts of the code because it's private, I'm only showing the part about the snack bar.Anyway, if you just put some console.log or alert in the snackBar function, it will pass it back nicely.The problem is the snack bar.here is my code:

 import React from 'react'
    import Snackbar from '@mui/material/Snackbar'
    const Camera=()=> {
  const [open, setOpen]=useState(false)
        const snackBar=(errorMessage)=> {
            return <Snackbar open={open} message={errorMessage}/>

        let callback={
                    error: function (error) {
                    if (error.code===100) {
                        return snackBar('error occured')
                    } else if (error.code===104) {
                        return snackBar('Please don't move the phone')
                    } else if (error.code===105) {
                        return snackBar('Try again')}
return (


Export default camera

uj5u.com enthusiastic netizens replied:

You are not calling a callback or snackBar anywhere, nor in any JSX.You also forgot to import useState.

If your intent is to provide a callback to handle errors (such as when fetching), then show Snackbar, here is an example of how to use a (very rough pseudocode) callback example

import { Snackbar } from "@mui/material"
import { useState } from "react"

const Camera=()=> {
  const [errorMessage, setErrorMessage]=useState(null)

  const callback=(error)=> {
    if(error.code==='100') {
      setErrorMessage('Message 100')
    } else if(error.code==='105') {
      setErrorMessage('Message 105')
    } //...add all your other else-ifs here

  return (
      {errorMessage && <Snackbar open={errorMessage} message= {errorMessage}/>}


Technical otaku

Sought technology together

Related Topic


Leave a Reply