Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router with a custom root and a base component

I have an integrated React app (it's integrated into an existing Flask app) and the entry to the React app is not on the site's root. The first URL that fires the React app is the '/active-items'.

However, other routes do not necessarily extend that path. Some of the routes are '/active-items/item/', while some are completely different, like '/item-selection'.

With that in mind, I'm trying to set up my React Router to provide a base component for each of those routes. Basically, any route that fires should have the 'App' component as the base component, and inside App component I have '{props.children}'.

I've tried several iterations of how the routes should look like, but with no luck.

My latest iteration is this:

<Router>
  <div>
    <Route path='/' component={App}>
      <Route path='active-items' component={ActiveItems} />
    </Route>
  </div>
</Router>

App is rendered, but ActiveItems is not. Any ideas how should I approach this?

EDIT: I'm using react-router-dom v4.0.0

like image 745
dnmh Avatar asked Mar 10 '23 13:03

dnmh


1 Answers

Original Answer

The version 4 of the React Router has a lot of breaking changes. You can't use nested routes this way anymore. Check out this example of nested routes using the new version of the React Router.

const Header = () => (
  <nav>
    <ul>
      <li>Home</li>
      <li>About</li>
    </ul>
  </nav>
)

const Footer = () => (
  <footer>
    Copyrights
  </footer>
)

const Layout = props => (
  <div className="layout">
    <div className="layout__container">
      <Header />{ props.children }
      <Footer />
    </div>
  </div>
)

const Home = () => <Layout>This is the home page.</Layout>
const About = () => <Layout>This is the about page.</Layout>

<Router>
  <div>
    <Route path="/" component={Home} />
    <Route path="/about" component={About} />
  </div>
</Router>

Hope it helps.

Updated Answer (November, 16th)

This is what I'm doing actually.

import { BrowserRouter, Route, Switch } from 'react-router-dom'
import React from 'react'

import About from './components/views/About'
import Home from './components/views/Home'
import Layout from './components/views/Layout'

const Routes = () => (
  <BrowserRouter>
    <Layout>
      <Switch>
        <Route exact path='/' component={Home} />
        <Route exact path='/about' component={About} />
      </Switch>
    </Layout>
  </BrowserRouter>
)

export default Routes
like image 144
Rafael Berro Avatar answered Mar 23 '23 06:03

Rafael Berro