Zanam
Zanam

Reputation: 4807

Dialog box doesn't click on onClick event

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

Answers (1)

dance2die
dance2die

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

Upvotes: 3

Related Questions