-1

I have Navbar which has to be rendered on every page. So I'm trying to get this through BrowserRouter like this:

import React, { Component } from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
import PublicLayout from './components/layouts/PublicLayout';
import Main from './components/pages/Main';
import Services from './components/pages/Services';

class App extends Component {
    render() {
        return (
            <BrowserRouter>
                <div className="App">
                    <Route component={ PublicLayout }>
                        <Route exact path='/' component={ Main } />
                        <Route exact path='/services' component={ Services } />
                    </Route>
                </div>
            </BrowserRouter>
        );
    }
}

export default App;

My PublicLayout is just navigation links. And I see it on the screen. But React doesn't render the Main page content. What I expect to see it just Hello World from Main page component below Navbar. What I'm doing wrong? Please help.

UPD: My PublicLayout code:

import React, { Component } from 'react';
import Navbar from '../nav/Navbar';

class PublicLayout extends Component {
    state = {
        items: [
            { id: 1, name: 'Услуги', link: '/services' },
        ]
    }

    render() {
        return (
            <div>
                <Navbar items={ this.state.items } />
                { this.props.children }
            </div>
        );
    }
}

export default PublicLayout;

UPD2: In browser console I see an error:

Warning: You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored
Nastro
  • 1,330
  • 1
  • 15
  • 32

3 Answers3

0

Am not sure why are you using PublicLayout, you can't use Route inside Route.

Create PublicLayout as child inside BrowserRouter. `

<BrowserRouter>
  <div className="App">
    <Route exact path="/" component={Main} />
    <Route exact path="/services" component={Services} />
  </div>
</BrowserRouter>
Amruth L S
  • 4,439
  • 1
  • 21
  • 38
0

Found an answer here. Since React v4 to wrap components you don't put anymore your Routes inside another Route, you put your Routes directly inside a component.

<Router>
    <MyLayout>
      <Route path='/abc' component={ABC} />
      <Route path='/xyz' component={XYZ} />
    </MyLayout>
</Router>
Nastro
  • 1,330
  • 1
  • 15
  • 32
0

Replace <Route component={ PublicLayout }> with <PublicLayout>

<PublicLayout>
    <Route exact path='/' component={ Main } />
    <Route exact path='/services' component={ Services } />
</PublicLayout>
Bhojendra Rauniyar
  • 73,156
  • 29
  • 131
  • 187