I'm kind of new to React stuff, I've been playing with it for like a week, and I'm stuck at pretty simple thing I think.
After user clicks "logout" I want the function logOut to also redirect him to other page (atm login page, cause its the only other page I've got). However, using navigate, I am having this error about Hooks.
Line 13:21: React Hook "useNavigate" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function
I've tried to workaround this however I don't think I fully understand whats the matter here. If anyone could simply point to me, what should I re-write to get my code going, I would be grateful.
My App.js:
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link, Routes } from 'react-router-dom';
import './App.css';
import RegistrationForm from './registry/Register';
import LoginForm from './registry/Login';
import WelcomeBack from './pages/Main';
import { useNavigate } from 'react-router-dom';
class App extends Component {
}
render() {
const nav = useNavigate();
function logOut() {
localStorage.removeItem("jwt");
nav("/login");
}
function isLoggedIn() {
const tokenValue = localStorage.getItem("jwt");
if (tokenValue != null) {
return true;
}
//here navigate to '/login'
return false;
}
return (
<Router>
<div>
<div id="myTopnav">
<a href="/" >Home</a>
<a href="#about">About</a>
<a href="/register" >Register</a>
<a href="/login" >Login</a>
<div className="logout" >
<a href="#" onClick={logOut}>Logout</a>
</div>
<a href="javascript:void(0);" onClick={myFunction}>
<i ></i>
</a>
</div>
<Routes>
<Route path='/register' element={<RegistrationForm />}/>
<Route path='/login' element={<LoginForm />} />
<Route path='/' element={<WelcomeBack />} />
</Routes>
</div>
</Router>
);
}
}
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className = " responsive";
}
else {
x.className = "topnav";
}
}
export default App;
CodePudding user response:
first thing you can't use react hooks ( useNavigate ) inside class component, instead you can use withRouter in class component. https://v5.reactrouter.com/web/api/withRouter
second thing, you forgot to put the code between the curly braces
you should do it like this:
class App extends Component {
...
// put your code here between the curly braces
}
CodePudding user response:
Hooks are not working in the class component, if u want to use you can wrap it in a HOC.
function withNavigation(Component) {
return props => <Component {...props} navigate={useNavigate()} />;
}
and then
class BlogPost extends React.Component {
redirect(){
this.props.navigate('/url')
}
render() {
// ...
}
}
export default withNavigation(BlogPost);
check this issue for more information Github Issue