blockhead
blockhead

Reputation: 431

Prevent keys that are not the enter key from triggering submit function

I am using a react components system(mantine). I have a select field and I want to select an option with any key and submit using the enter key only.

The problem right now is that once the dropdown appears and I press any key it calls the function and sends the empty string i set. The onSubmit won't work without a submit button present in the form, setting display as none still didn't get it to submit. So, I resulted to this.

import React, { useState, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { Text, Select } from "@mantine/core";
import { Icon } from "@iconify/react";
import axios from "axios";
import { api } from "../helpers/api";

const Home = () => {
  const [joblist, setJoblist] = React.useState("");
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);
  const history = useNavigate();
  const selectForm = useRef(null);
  function handleSubmit(e) {
    if (e.key === "Enter" && e.preventDefault()) {
      selectForm.current.submit();
    }

    setJoblist("");
    console.log(joblist);
    setLoading(true);
    const uu = {
      jobs: joblist,
    };
    console.log(uu);
    console.log(api.jobs);
    fetch(api.jobs, {
      method: "POST",
      headers: {
        "Access-Control-Allow-Origin": "http://127.0.0.1:8000/",
        "Content-Type": "application/json",
      },
      body: JSON.stringify(uu),
    })
      .then((res) => {
        console.log(res.data);
        setLoading(false);
      })
      .catch((err) => {
        console.log(err);
        setLoading(false);
        setError(err.message || err);
      });
  }

  return (
    <div>
    
      <form ref={selectForm} onKeyDown={handleSubmit}>
        <Select
          label="Your favorite framework/library"
          placeholder="Pick one"
          searchable
          clearable
          nothingFound="No options"
          value={joblist}
          onChange={setJoblist}
          data={[
            { value: "react", label: "React" },
            { value: "ng", label: "Angular" },
            { value: "svelte", label: "Svelte" },
            { value: "vue", label: "Vue" },
          ]}
          style={{
            width: "608px",
            marginLeft: "294px",
            marginTop: "-100px",
          }}
        />
      </form>
    </div>
  );
};

export default Home;

Upvotes: 0

Views: 1937

Answers (1)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

With

if (e.key === "Enter" && e.preventDefault()) {
  selectForm.current.submit();
}

When e.key === "Enter" is false, the condition evaluation stops right there. So try:

e.preventDefault()
if (e.key === "Enter") {
  selectForm.current.submit();
}

And you may need this to prevent executing the rest of the code (but that is unclear...)

else {
  return
}

Upvotes: 1

Related Questions