In my App.js file of the application, I am setting the routes of the app.
This is the code of my App.js file
import React, {useEffect} from "react";
import {Container} from '@material-ui/core';
import {BrowserRouter, Routes, Route, Navigate} from 'react-router-dom';
import { gapi } from 'gapi-script';
import Navbar from "./components/Navbar/Navbar";
import Home from './components/Home/Home';
import Auth from "./components/Auth/Auth";
import MealsPage from "./components/MealsPage/MealsPage";
import WorkoutDetails from "./components/WorkoutDetails/WorkoutDetails";
const App=()=>{
const user=JSON.parse(localStorage.getItem('profile'));
useEffect(() => {
const start = () => {
gapi.auth2.init({
clientId: process.env.REACT_APP_GOOGLE_API_TOKEN,
scope: ""
})
};
gapi.load('client:auth2', start);
})
return(
<BrowserRouter>
<Container maxWidth="xl">
<Navbar/>
<Routes>
<Route path="/" exact ={()=>{<Navigate to="/workouts"/>}}/>
<Route path="/workouts" exact element={<Home/>}/>
<Route path="/workouts/search" exact element={<Home/>}/>
<Route path="/workouts/:id" element={<WorkoutDetails/>}/>
<Route path="/meals" exact element={<MealsPage/>}/>
<Route path="/auth" exact element={()=>{!user? <Auth/>:<Navigate to="/workouts"/>}}/>
</Routes>
</Container>
</BrowserRouter>
);
}
export default App;
I am getting an error that says this:
react-dom.development.js:67
Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
I assume it is from the Auth route as it does not specify an element to render when we have that specific route, but it specifies a function. Basically, when the user is logged in, he should not see the auth component because he is already logged in and he should be redirected to the '/workouts' route which is another page in the application.
Could you help me solve this?
CodePudding user response:
Here
element={()=>{!user? <Auth/>:<Navigate to="/workouts"/>}}
.
Try it like element={user? <Navigate to="/workouts"/> : <Auth/>}
or return component like element={()=>!user? <Auth/>:<Navigate to="/workouts"/>}
or
element={()=>{return !user? <Auth/>:<Navigate to="/workouts"/>}}
CodePudding user response:
Looking at the documentation for <Route />
, the element
prop is meant to be an element - not a function returning an element.
Therefore, you should simply be able to remove the function call and pass the element directly:
<Route
path="/auth"
exact
element={!user ? <Auth/> : <Navigate to="/workouts"/>}
/>