'React/TS prevent form submission on enter while using "required" tag

There are already a bunch of helpful answers on preventing form submit on enter (example1, example2) However none of these work if I want to include the "required" tag on any of the inputs. See code below:

    
    const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        // do other stuff
    };
    
    return (
            <form id="LocationForm" onSubmit={handleSubmit} >
                <input type="text" placeholder="Please add country" onKeyUp={handleCountryChange} />
                <input type="text" placeholder="Please add city" onKeyUp={handleCityChange} required />
                <input type="submit" value="Submit" />
            </form>
    )

When I press enter in the first input, a dialog pops up that says "This field is required". Ideally, I only want this to pop up when I click the submit button and not when I press enter in any other input. Of course I could implement this logic myself without using the required tags, but would rather avoid re-inventing the wheel here... unless there is some other standard practice that people use. Any pointers?



Solution 1:[1]

Try adding onKeyPress={(e) => e.preventDefault() to the <form>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 maxpsz