Stack Overflow Asked by Udo Held on December 22, 2021
I build a little React Routing application and wanted to test forwarding to a different react page after a successful HTTP response from a form submit.
When clicking on the submit button the submit confirmation screen in red will be shown, however, shortly afterwards the browser will be forwarded back to the original screen with the form parameters added "/?dummy=dummy". If I do the redirect outside of the promise e.g. before the HTTP call the submit confirmation screen will stay.
Are there useful alternatives to achieve a similar behavior?
Routing setup:
export default function App() {
return (<Router>
<Switch>
<Route path="/" exact component={TestForm} />
<Route path="/submitted" component={Submitted} />
</Switch>
</Router>
);}
The testing component:
class TestForm extends Component {
submitHandler = () => {
let history = this.props.history;
fetch("https://reqres.in/api/users/6")
.then(response => {
history.push({ pathname: "/submitted" });
});
};
render() {
return (<div>
<form onSubmit={this.submitHandler}>
<input type="text" name="dummy" value="dummy" readOnly /><input type="submit" />
</form>
</div>);}}
export default withRouter(TestForm);
Submit confirmation component:
const submitted = props => {
let style = { "background-color": "red" };
return <div style={style}>Form has been submitted</div>;
};
The full code and behavior can be tested in a sandbox.
It is because you do not prevent the default function of the form submit event and it is posting the results.
Update your event handler to prevent the default.
import React, { Component } from "react";
import { withRouter } from "react-router-dom";
class TestForm extends Component {
submitHandler = (e) => {
e.preventDefault()
let history = this.props.history;
fetch("https://reqres.in/api/users/6")
.then(response => {
history.push({ pathname: "/submitted" });
})
.catch(myError => {
console.log(myError);
});
};
render() {
return (
<div>
<form onSubmit={this.submitHandler}>
<input type="text" name="dummy" value="dummy" readOnly />
<input type="submit" />
</form>
</div>
);
}
}
export default withRouter(TestForm);
Answered by Jacob Smit on December 22, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP