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
JavaScript
x
30
30
1
import React, { useState } from "react";
2
import { Snackbar, Alert } from "@mui/material";
3
4
const AlertComponent = () => {
5
const [open, setOpen] = useState(false);
6
const handleClick = () => {
7
setOpen(true);
8
};
9
10
const handleClose = (event, reason) => {
11
if (reason === "clickaway") {
12
return;
13
}
14
15
setOpen(false);
16
};
17
return (
18
<div>
19
{" "}
20
<Snackbar open={open} autoHideDuration={6000} onClose={handleClose}>
21
<Alert onClose={handleClose} severity="success">
22
Successfully Submitted!
23
</Alert>
24
</Snackbar>
25
</div>
26
);
27
};
28
29
export default AlertComponent;
30
Parent Component
JavaScript
1
19
19
1
const ParentComponent = () => {
2
const [open, setOpen] = useState(false);
3
4
const onSubmit = async (data) => {
5
//codes to submit the data
6
setOpen(true); //trigger the alert component
7
8
};
9
10
return (
11
<div>
12
//form here to submit
13
<AlertComponent open={open} />
14
</div>
15
);
16
};
17
18
export default ParentComponent;
19
How can I fix this? Thank you.
Advertisement
Answer
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
JavaScript
1
18
18
1
import React from "react";
2
import { Snackbar, Alert } from "@mui/material";
3
function AlertComponenet(props) {
4
const { open, handleClose } = props;
5
return (
6
<div>
7
{" "}
8
<Snackbar open={open} autoHideDuration={6000} onClose={handleClose}>
9
<Alert onClose={handleClose} severity="success">
10
Successfully Submitted!
11
</Alert>
12
</Snackbar>
13
</div>
14
);
15
}
16
17
export default AlertComponenet;
18
Parent Component (In my code-sandbox I used App.js)
JavaScript
1
27
27
1
import React, { useState } from "react";
2
import "./styles.css";
3
import AlertComponent from "./AlertComponent";
4
5
export default function App() {
6
const [open, setOpen] = useState(false);
7
const handleClick = () => {
8
setOpen(true);
9
};
10
11
const handleClose = (event, reason) => {
12
if (reason === "clickaway") {
13
return;
14
}
15
16
setOpen(false);
17
};
18
return (
19
<div className="App">
20
<h1>Hello CodeSandbox</h1>
21
<h2>Start editing to see some magic happen!</h2>
22
<button onClick={handleClick}>Show Alert</button>
23
<AlertComponent open={open} handleClose={handleClose} />
24
</div>
25
);
26
}
27