Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Close React Modal With Form Submit

Hello there I’m trying to figure out how to close this modal and submit a new item at the same time… right now it’s only doing one or the other. If I put Submit at the bottom there it wont submit the information in the form and if I take away {props.onClose} then it’ll add the item but I have to refresh to close the modal.

const NewProposal = (props) => {
  const titleRef = useRef("");
  const proposalRef = useRef("");

  function submitHandler(event) {
    event.preventDefault();

    // could add validation here...

    const proposal = {
      title: titleRef.current.value,
      proposal: proposalRef.current.value,
      profilepic: "https://niftyapenation.com/static/media/logo.d41d77f3.png",
      count: 555,
      user: "Ape Nation",
    };

    props.onAddProposal(proposal);
    
  }

  return (
    <Modal onClose={props.onClose}>
      <form className={classes.form} onSubmit={submitHandler}>
        <button className={classes.close} onClick={props.onClose}>
          x
        </button>
        <label htmlFor="title">Title</label>
        <input
          type="text"
          className={classes.title_input}
          ref={titleRef}
        ></input>
        <label>Your Proposal</label>
        <textarea
          type="text"
          id="name"
          className={classes.proposal_input}
          ref={proposalRef}
        ></textarea>
        <button onClick={props.onClose} type="submit"  className={classes.post}>Add Proposal</button>
      </form>
    </Modal>
  );
};

export default NewProposal;

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Add props.onClose() in your submitHandler function.

function submitHandler(event) {
    event.preventDefault();

    // could add validation here...

    const proposal = {
      title: titleRef.current.value,
      proposal: proposalRef.current.value,
      profilepic: "https://niftyapenation.com/static/media/logo.d41d77f3.png",
      count: 555,
      user: "Ape Nation",
    };

    props.onAddProposal(proposal);
    props.onClose()
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading