1
votes

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.

1
your button is of type submit this means that the form will submit when you click it. a form submit, submits the webpage (aka page refresh). Instead specify a different type for the button (like <button type="button"). You should probably put a onSubmit on your form element too - John Ruddell

1 Answers

3
votes

The page is refreshing as the button's type is "submit" which triggers the page to refresh.

You can follow along by forking Sandbox. Edit so.answer.56695455

So you can stop the issue in two different ways.

1 Remove "type=submit"

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. demo

2 Prevent default on button click event.

 <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().

enter image description here