Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router V4 Routers with Master Pages / Templates

I am relatively new to react and attempting to create an app that has 2 designs. One is the public site that has a common header and footer and the internal app which has an admin header and side bar. I created a Router and 2 main routes '/' and '/app'. I then added subroutes hoping that if the parent routers were matched, it would show the parent component and pass the sub route's component as the this.props.children. I seemed to have done it wrong. Here is what I created.

App.js:

...
class App extends Component {
  render() {
    return (
      <Router>
        <Switch>
          <Route component={Public}>
            <Route exact path="/" component={Home}/>
            <Route path="/login" component={Login}/>
          </Route>
          <Route component={Main}>
            <Route path="/dash" component={Dash}/>
            <Route path="/people" component={People}/>
          </Route>
        </Switch>
      </Router>
    );
  }
}
...

Public 'template':

...
render(){
    return(
      <div>
        I am a public page
        {this.props.children}
      </div>

    )
  }
...

Home.js

...
class Home extends Component{
  render(){
    return(

      <div>I am the home page</div>
    )
  }
}
...

App 'template'

...
class Main extends Component{
  render(){
    return(
      <div>
        <Header />
        <div>I am an app page</div>
        {this.props.children}
        <Footer/>
      </div>
    )
  }
}
...

Dash.js

...
class Dash extends Component{
  render(){
    return(
      <div>I am the dash page</div>

    )
  }
}
...

Thanks and if any one can tell me or point me to a good resource I would appreciate it!

like image 638
Wally Kolcz Avatar asked Jan 28 '23 20:01

Wally Kolcz


1 Answers

You're really close! What you need to do is actually put the template components as the parent not in a <Route /> component. A components children are the components in between its start and end tag. Keep on trucking !

class App extends Component {
   render() {
       return (
          <Router>
           <Switch>
             <Public>
               <Route exact path="/" component={Home}/>
               <Route path="/login" component={Login}/>
             </Public >
             <Main>
               <Route path="/dash" component={Dash}/>
               <Route path="/people" component={People}/>
             </Main>
           </Switch>
         </Router>
       );
     }
   }
like image 157
Djtouchette Avatar answered Jan 30 '23 12:01

Djtouchette