so i made a snackbar.
In my case, I use the snackbar for notification that successfully added data, instead of the snackbar appearing, I get 3 kind of error
Warning: Failed prop type: Invalid prop 'children' supplied to 'ForwardRef(Alert)', expected a ReactNode
Error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.
console.js:288 The above error occurred in the <div> component:
Anyone know how to fix this error, this is my first time got this kind of error, and also here’s my snackbar code
import React, { createContext, useContext, useState, forwardRef } from "react";
import Snackbar from "@mui/material/Snackbar";
import MuiAlert from "@mui/material/Alert";
const Alert = forwardRef(function Alert(props, ref) {
return <MuiAlert elevation={6} ref={ref} variant="filled" {...props} />;
});
const SnackbarContext = createContext();
export const useSnackbar = () => {
return useContext(SnackbarContext);
};
const SnackbarProvider = ({ children }) => {
const [snackbar, setSnackbar] = useState({
open: false,
message: "",
severity: "info",
});
const showSnackbar = (message = "", severity = "info") => {
setSnackbar({ open: true, message: message || "No message", severity });
};
const handleClose = (event, reason) => {
if (reason === "clickaway") {
return;
}
setSnackbar({ ...snackbar, open: false });
};
return (
<SnackbarContext.Provider value={showSnackbar}>
{children}
{snackbar.open && snackbar.message && (
<Snackbar
open={snackbar.open}
autoHideDuration={6000}
onClose={handleClose}
anchorOrigin={{ vertical: "top", horizontal: "center" }}
>
<Alert
onClose={handleClose}
severity={snackbar.severity}
sx={{ width: "100%" }}
>
{snackbar.message}
</Alert>
</Snackbar>
)}
</SnackbarContext.Provider>
);
};
export default SnackbarProvider;
I tried to make default message but it doesn’t do anything, does the backend also affect? because previously this problem did not occur, or the cause is where my snackbar is used?
2
Answers
I would like to ask permission to tag you in this post. Thank you so much for understanding! Sure, here's the main problem `
` I don't know why that part causes an error, even though the way to use the snackbar in other files is the same as using showSnackbar() Is it because i put it inside then?
My guess is that you are passing an object instead of a string to your
showSnackbar
method. so thesnackbar.message
became an object and thus not a valid child