Answer the question
In order to leave comments, you need to log in
Does routing have to be inside app.js?
I read about routing in react, and everywhere examples are given inside app.js. But for me, for example, it would be convenient to register routing inside another file, one nesting level lower.
for example: app.js would look like this :
class App extends React.Component{
render() {
return(
<div className="App">
<Header state={this.props.state}/>
<Content state={this.props.state}/>
<Footer />
</div>
)
}
}
Answer the question
In order to leave comments, you need to log in
no, import the routing from somewhere else
render() {
return(
<div className="App">
{routes}
<Footer />
</div>
)
}
}
import React from 'react';
import {BrowserRouter as Router} from 'react-router-dom';
import {useRoutes} from './routes';
import {useAuth} from './hooks/auth.hook'
import {AuthContext} from './context/AuthContext'
import 'bootswatch/dist/sketchy/bootstrap.min.css'
function App() {
const {token, login, logout, userId} = useAuth()
const isAuthenticated = !!token
const routes = useRoutes(isAuthenticated)
return (
<AuthContext.Provider value={{token, login, logout, userId, isAuthenticated}}>
<Router>
<div className="App container">
{routes}
</div>
</Router>
</AuthContext.Provider>
);
}
export default App;
import React from 'react'
import {Switch, Route, Redirect} from 'react-router-dom'
import AdminPage from './pages/AdminPage'
import MainPage from './pages/MainPage'
import AuthPage from './pages/AuthPage'
import PostPage from './pages/PostPage'
export const useRoutes = isAuthenticated =>{
if(isAuthenticated){
return(
<Switch>
<Route path="/admin" exact>
<AdminPage/>
</Route>
<Redirect to="/admin"/>
</Switch>
)
}
return(
<Switch>
<Route path="/" exact>
<MainPage/>
</Route>
<Route path="/post/:id" exact>
<PostPage/>
</Route>
<Route path="/login" exact>
<AuthPage/>
</Route>
<Redirect to="/"/>
</Switch>
)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question