Reputation: 1829
I have this Alert component to be used just to have a message that says "Successfully submitted" and I'm trying to use thin in a parent component. However, nothing shows in the parent component.
AlertComponent
import React, { useState } from "react";
import { Snackbar, Alert } from "@mui/material";
const AlertComponent = () => {
const [open, setOpen] = useState(false);
const handleClick = () => {
setOpen(true);
};
const handleClose = (event, reason) => {
if (reason === "clickaway") {
return;
}
setOpen(false);
};
return (
<div>
{" "}
<Snackbar open={open} autoHideDuration={6000} onClose={handleClose}>
<Alert onClose={handleClose} severity="success">
Successfully Submitted!
</Alert>
</Snackbar>
</div>
);
};
export default AlertComponent;
Parent Component
const ParentComponent = () => {
const [open, setOpen] = useState(false);
const onSubmit = async (data) => {
//codes to submit the data
setOpen(true); //trigger the alert component
};
return (
<div>
//form here to submit
<AlertComponent open={open} />
</div>
);
};
export default ParentComponent;
How can I fix this? Thank you.
Upvotes: 1
Views: 2937
Reputation: 81
Although @Ghader Salehi commented already the solution but if anyone is not sure how to control the alert from parent here is the code.
AlertComponent.js
import React from "react";
import { Snackbar, Alert } from "@mui/material";
function AlertComponenet(props) {
const { open, handleClose } = props;
return (
<div>
{" "}
<Snackbar open={open} autoHideDuration={6000} onClose={handleClose}>
<Alert onClose={handleClose} severity="success">
Successfully Submitted!
</Alert>
</Snackbar>
</div>
);
}
export default AlertComponenet;
Parent Component (In my code-sandbox I used App.js)
import React, { useState } from "react";
import "./styles.css";
import AlertComponent from "./AlertComponent";
export default function App() {
const [open, setOpen] = useState(false);
const handleClick = () => {
setOpen(true);
};
const handleClose = (event, reason) => {
if (reason === "clickaway") {
return;
}
setOpen(false);
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={handleClick}>Show Alert</button>
<AlertComponent open={open} handleClose={handleClose} />
</div>
);
}
Upvotes: 4