0

I want to make a form that disappears if I click outside of it.

Form Component:

const CreateTaskPopup = (props) => {
  
  const ref = query(collection(db, "tasks"));
  const mutation = useFirestoreCollectionMutation(ref);

  useEffect(() => {
    const closeTaskPopup = (event) => {
      if (event.target.id != "addForm") {
        props.setTrigger(false)
      }
    }
    document.addEventListener('click', closeTaskPopup);

    return () => document.removeEventListener('click', closeTaskPopup)
  }, [])

  return (props.trigger) ? (
      <>
        <div className="bg-darkishGrey my-4 p-1 mx-3 ml-16 cursor-pointer block"
        id="addForm">
          <div className="flex justify-between">
            <div className="flex break-all items-center ">
              <Image src={fileIcon} className="w-6 mx-2"/>
              <div>
              <Formik
                initialValues={{
                  taskName: "",
                  taskIsDone: false,
                  parentId: props.parentId ? props.parentId : "",
                  hasChildren: false,
                }}
                onSubmit={(values) => {
                  mutation.mutate(values);
                  props.setTrigger(false);
                }}
              >
                <Form>
                  <div className="">
                    <TextInput
                      placeholder="Type a name"
                      name="taskName"
                      type="text"
                    />
                  </div>
                </Form>
                </Formik>
              </div>
            </div>
            <div className="flex items-center">
            </div>
          </div>
        </div>
      </>
  ) : null
}

export default CreateTaskPopup

Text Input Component:

import { useField } from "formik";

const TextInput = ({ label, ...props}) => {
  const [field, meta] = useField(props);
  return (
    <div>
      <label id="addForm" className="text-lightestGrey text-xl block" 
      htmlFor={props.id || props.name}>
        {label}
      </label>
      <input id="addForm" className="bg-darkishGrey text-xl text-almostWhite my-2 
      outline-none w-10/12 rounded-sm p-1 mx-3" {...field} {...props} />
      {meta.touched && meta.error ? <div>{meta.error}</div>: null}
    </div>
  );
};

export default TextInput;

I tried giving an id to the elements inside it but it's not the best solution as it has components from the Formik library to which I can't assign an id. I don't know what would be the best solution for this problem.

Kariko
  • 1
  • 1
  • your answer can be found [here](https://stackoverflow.com/questions/1403615/use-jquery-to-hide-a-div-when-the-user-clicks-outside-of-it). it contains jquery and js both solutions. – Chintan Trivedi Dec 08 '22 at 20:23

0 Answers0