A
A
Alex_mersvg2020-11-19 15:27:46
React
Alex_mersvg, 2020-11-19 15:27:46

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>
        )
    }
}

And already inside the "Content" component place the routing of my application. This seems to be a completely working option, but I wonder whether such a routing implementation is accepted or allowed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vovash, 2020-11-19
@Alex_mersvg

no, import the routing from somewhere else

render() {
        return(
            <div className="App">
                {routes}
               <Footer />
            </div>
        )
    }
}

here is my plush example with authorization
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 question

Ask a Question

731 491 924 answers to any question