Home > database >  Close React Modal With Form Submit
Close React Modal With Form Submit

Time:08-06

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;

CodePudding user response:

Try this

  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();
    
  }

CodePudding user response:

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()
  }
  • Related