I am now working on routing after login in successfully. But got this error:
Uncaught TypeError: Cannot read properties of undefined (reading 'navigate')
Here is the login page
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
loginName: "",
password: "",
loginNameError: null,
passwordError: null,
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
this.props.navigation.navigate("/employee")
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div className="input-container">
<label>User ID</label>
<input type="text" name="loginName" value={this.state.loginName} onChange={(e) => (this.setState({ loginName: e.target.value }))} />
<p>{this.state.loginNameError}</p>
</div>
<div className="input-container">
<label>Password</label>
<input type="password" name="password" value={this.state.password} onChange={(e) => (this.setState({ password: e.target.value }))} />
<p>{this.state.passwordError}</p>
</div>
<div className="button-container"><input type="submit" value="CONNECT"></input></div>
</form>
);
}
}
export default Login;
Here is the APP.js
function App() {
return (
<div >
<BrowserRouter>
<Routes>
<Route path="/employee" element={<UserManagement />}></Route>
<Route path="/login" element={<Login />}></Route>
</Routes>
</BrowserRouter>
</div>
);
}
export default App;
how to solve this error?
CodePudding user response:
Since react router v6 doesnt have withRouter
// https://reactrouter.com/docs/en/v6/getting-started/faq#what-happened-to-withrouter-i-need-it
import {
useLocation,
useNavigate,
useParams,
} from "react-router-dom";
function withRouter(Component) {
function ComponentWithRouterProp(props) {
let location = useLocation();
let navigate = useNavigate();
let params = useParams();
return (
<Component
{...props}
router={{ location, navigate, params }}
/>
);
}
return ComponentWithRouterProp;
}
// then in the Login class component you can consume withRouter
handleSubmit(event) {
event.preventDefault();
// consume `router` prop
this.props.router.navigate("/employee");
}
// Wrap Login in withRouter HOC to make sure `router` prop is available
export default withRouter(Login);
// export default Login;
This said, I would recommend using react-router with a function component, not a class component.
CodePudding user response:
Because using of class component you can not use hooks! but I think this work here:
this.props.history.push("/employee");