I am having this weird issue when I press the button the submit refreshes the page and attaches to the browsers URL parameters. Seems that preventDefault() not getting called.
The function that triggers onSubmit is this one:
const handleLogin = (e: FormEvent<HTMLFormElement>) => {
console.log("triggered?")
e.preventDefault()
...some api calls
}
At first when I press the button (input[submit]) seems that this function is not getting called at all as it gets refreshed. But after this first call it attaches to the URL the form input fields and their values (which is quite bad because it exposes f.ex password to the URL).
the jsx of form looks like this:
<form onSubmit={handleLogin}>
...input elements
...
<div className={'form-group'}>
<input className="form-control"
value={"Login"}
name="login" type="submit"/>
</div>
</form>
EDIT:
So i've noticed that this issue happens because of react-router (v6);
<Routes>
<Route path="/" element={<Navigate to="ui"} />
<Route path="ui">
<Route index element={getRedirect()}/>
<Route path="login" element={<AuthPage/>}/>
</Route>
</Routes>
Because the moment the page loads react router makes "redirection" to /ui/ - localhost:port/ui/
And thats why on first click e.preventDefault() or e.stopPagination() doesnt'work . But if i refresh or go straight to localhost:port/ui/ instead of just localhost:port . The form will work as it should. Honestly i couldn't find a good solution for this :\
Currently i added something like this for dev env (in prod BE should redirect to /ui/ ) .
if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
if (!window.location.href.includes("/ui/")) {
window.location.href = window.location.href + "ui/"
}
But this looks very dodgy to me.
I think you are making some mistake here is the totally working example that's work perfectly fine.
const App = () => {
const [value, setValue] = useState("");
const handleChange = (event) => {
console.log(event.target.value);
setValue(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
console.log(value);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={value} onChange={handleChange} />
</label>
<input type="submit" value="Login" name="login" />
</form>
);
};
export default App;