I am trying to redirect my component when submitting a form. But the problem is I am not getting this.props.history in the component. How to accomplish my task like this.props.history.push('/newpage') when I submitting a form?
I have given my code for component below
import React, { Component } from 'react';
class Login extends Component {
state = { name: "", email: "", password: "", };
onChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
onSubmit = e => {
e.preventDefault();
this.props.callbackFromParent(this.state);
this.props.history.push('/welcome')
};
render() {
return (
<React.Fragment>
<form onSubmit={this.onSubmit}>
<input
placeholder="Enter name.."
type="text"
name="name"
value={this.state.value}
onChange={this.onChange}
/>
<input
placeholder="Enter email.."
type="email"
name="email"
value={this.state.value}
onChange={this.onChange}
/>
<input
placeholder="Set password.."
type="password"
name="password"
value={this.state.value}
onChange={this.onChange}
/>
<button type="submit">Submit</button>
</form>
</React.Fragment>
);
}
}
export default Login;
Any help would be appreciated!
Sonu Sasankan
Creative coder
You need to make "history" object available to all the components down the line then only you can use it.
You need to wrap it inside withRouter
...
import { withRouter } from "react-router-dom";
...
...
...
...
export default withRouter(Login);
Sebastian
Well you different options here: