Search code examples
javascriptreactjsreact-statemobx-react-form

Unable to submit form in Model react


I have a model file in which I want to submit form but I am not able to trigger submit function my file is like

import React, { useState, useEffect } from "react";
import InputField from "./InputField";
import Button from "./Button";
import axios from "axios";
import { Modal, ModalHeader, ModalBody, ModalFooter } from "reactstrap";

function ArticleOptionsModal(props) {
  const [articleOption, setArticleOption] = useState("");
  useEffect(() => {
    if (typeof props.articleopt === "undefined") {
      setArticleOption("");
      console.log("hhiii");
    } else {
      setArticleOption(props.articleopt.optionname);
      console.log("hhiii");
    }
  }, [props]);

  return (
    <form onSubmit={e => handleSubmit(e)}>
    <Modal isOpen={props.modal} toggle={props.toggle}>
      <ModalHeader toggle={props.toggle}>Times</ModalHeader>
      <ModalBody>
            <div className='row'>
              <div className='col-sm-6'>
                <div className='form-group text-left'>
                  <label htmlFor='' className='small'>
                    Name
                  </label>
                  <InputField
                    name='username'
                    placeholder={"Enter Name"}
                    value={articleOption.optionname}
                    onChange={e => changeOptionName(e)}
                  />            
               </div>
            </div>
        )}
      </ModalBody>
      <ModalFooter>
        <Button
          name={"Submit"}
          type='submit'
          btnLongWidth={false}
          onClick={props.toggle}
        />
        <Button
          name={"Cancel"}
          dangerButton={true}
          btnLongWidth={false}
          onClick={props.toggle}
        />
      </ModalFooter>
    </Modal>
  </form>
  );
  function changeOptionName(e) {
    setArticleOption(e.target.value);
  }
  function handleSubmit(e) {
    console.log("hiiiiii");
  }
}

export default ArticleOptionsModal;

Here handleSubmit is not triggering when I try to submit form. I tried using diff methods to just trigger this submit method but till now no luck . Any kind of help would be highly appreciated.


Solution

  • The form tag needs to be inside the modal component as otherwise, the event doesn´t bubble up correctly.

    As commented, I would suggest using a form library to handle the form management.

    Personally I suggest Final Form: https://github.com/final-form/react-final-form