'About Invalid hook call
Goal:
Make this react TS application to be working without any error.
Problem:
I get this problem:
"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:"
Still can't find the main problem.
What part am I missing?
Stackblitz:
https://stackblitz.com/edit/react-ts-pzzr8s?file=Login.tsx
Thank you!
import React, { useEffect, useState } from 'react';
import { render } from 'react-dom';
import {
BrowserRouter as Router,
Link,
Route,
Routes,
Navigate,
} from 'react-router-dom';
import Home from './Home';
import Login from './Login';
const App: React.FC = () => {
const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
useEffect(() => {
console.log('Authentication state - ', isAuthenticated);
}, [isAuthenticated]);
const handle_login = () => {
setIsAuthenticated(true);
};
const handle_logout = () => {
setIsAuthenticated(false);
};
const authenticatedRoutes = (
<Routes>
<Route
path="/home"
component={() => <Home handle_logout={handle_logout} />}
/>
<Navigate to="/home" />
</Routes>
);
const nonAuthenticatedRoutes = (
<Routes>
<Route
exact
path="/login"
component={() => <Login handle_login={handle_login} />}
/>
<Navigate to="/login" />
</Routes>
);
return (
<Router>
{/* <IonRouterOutlet> */}
{isAuthenticated ? authenticatedRoutes : nonAuthenticatedRoutes}
{/* </IonRouterOutlet> */}
</Router>
);
};
render(<App />, document.getElementById('root'));
import React from 'react';
interface HomeProps {
handle_logout: () => void;
}
const Home: React.FC<HomeProps> = (props) => {
return (
<React.Fragment>
<header>
{/* <h2>Home </h2> */}
<button slot="end" onClick={props.handle_logout}>
{' '}
Logout{' '}
</button>
</header>
<title> Home </title>
<div className="container">
<strong>Home page</strong>
<p>Click logout on the titlebar to logout </p>
</div>
</React.Fragment>
);
};
export default Home;
import React from 'react';
interface LoginProps {
handle_login: () => void;
}
const Login: React.FC<LoginProps> = (props) => {
return (
<React.Fragment>
<title> Login </title>
<div className="container">
<strong>login page</strong> <br />
<br />
<button onClick={props.handle_login}> Login </button>
</div>
</React.Fragment>
);
};
export default Login;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
