I have a react project which defines a Signup element in a file. The code is
import React, { Component } from 'react';
import Button from 'react-bootstrap/Button';
import Form from 'react-bootstrap/Form';
import { useNavigate } from 'react-router-dom';
import postData from './APIREQ';
class Signup extends Component {
state = {
email: "",
password: ""
};
onSubmit = (e) => {
e.preventDefault();
console.log(this.state.email);
console.log(this.state.password);
postData('http://localhost:5000/users', { email: this.state.email, password: this.state.password })
.then(data => {
console.log(data);
const navigate = useNavigate();
navigate('/');
});
}
render() {
return (
<div className="container">
<Form>
<Form.Group className="mb-3" controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control type="email" placeholder="Enter email" value={this.state.email} onChange={e => this.setState({ email: e.target.value})}/>
<Form.Text className="text-muted">
We'll never share your email with anyone else.
</Form.Text>
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control type="password" placeholder="Password" value={this.state.password} onChange={e => this.setState({ password: e.target.value})}/>
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicCheckbox">
<Form.Check type="checkbox" label="Check me out" />
</Form.Group>
<Button variant="primary" type="submit" onClick={this.onSubmit}>
Submit
</Button>
</Form>
</div>
);
}
}
export default Signup;
When the form is submitted I want to redirect to the homepage (Hosted at /). However, the current code gives an error of
react-dom.development.js:16063 Uncaught (in promise) Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
at Object.throwInvalidHookError (react-dom.development.js:16063:1)
at useContext (react.development.js:1613:1)
at useInRouterContext (hooks.tsx:61:1)
at useNavigate (hooks.tsx:140:1)
at Signup.js:22:1
I have looked at every search result for this but none of them work. The link it gives says that they must be called in the body of a function componnet, but how do I make this a function component while maintaining state? Thanks!