Reputation: 4807
I have the following code I am using as a tutorial:
CommentSend.js
import React, { useState } from "react";
import Dialog from "@material-ui/core/Dialog";
import FormControl from "@material-ui/core/FormControl";
import Button from "@material-ui/core/Button";
import Input from "@material-ui/core/Input";
import InputLabel from "@material-ui/core/InputLabel";
const CommentSend = () => {
const [description, setDescription] = useState("");
const [open, setOpen] = useState(false)
return (
<form>
<Button
onClick={() => setOpen(true)}
type="submit"
>
Add Comment
</Button>
<Dialog
open={open}
>
<FormControl fullWidth>
<InputLabel htmlFor="comment">Comment</InputLabel>
<Input
id="comment"
onChange={event => setDescription(event.target.value)}
/>
</FormControl>
</Dialog>
</form>
);}
export default CommentSend;
After clicking the button, the dialog box doesn't open up instead page refreshes. I am not sure what is going on here.
Upvotes: 1
Views: 906
Reputation: 36895
The page is refreshing as the button's type is "submit" which triggers the page to refresh.
You can follow along by forking Sandbox.
So you can stop the issue in two different ways.
const CommentSend = () => {
// ... redacted for brevity
return (
<form>
<Button
onClick={e => {
setOpen(true);
}}
>
Add Comment
</Button>
<Dialog open={open}>
// ... redacted for brevity
</Dialog>
</form>
);
};
Check out the working demo below.
<Button
onClick={e => {
e.preventDefault();
setOpen(true);
}}
type="submit"
>
Should you need to keep the type="submit"
for the button, you can prevent the refresh using the event passed to "onClick" callback and call .preventDefault()
.
Upvotes: 3