1

I used a React-Router, coded this

<Router>
  <div className="app">
    <div className="wrapper">
      <AppHeaderMain />
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/list/" component={List} />
        <Route path="/about/" component={About} />
        <Route component={NotFound} />
      </Switch>
      <div className="menu">
        <ul>
          <li><NavLink exact to="/">List</NavLink></li>
          <li><NavLink to="/about/">About</NavLink></li>
        </ul>
      </div>
    </div>
  </div>
</Router>

and I have a question, is it possible to load another component based on Rout path, for example:

path="/" - load <AppHeaderMain />
path="/list/" - load <AppHeaderSubpage />

I know I could insert a AppHeader component into each single component but I would like to don't repeat some additional code which would be required to make that. I mean something like conditional including (loading) component. Is it a good practice? Maybe I must to do exactly how I wrote: include in each single component?

1
  • you can add switch and route inside of <AppHeaderMain /> and decide how to render it. but Krasimir answer is a better practice. Commented Jan 1, 2018 at 20:43

1 Answer 1

2

I think it is a matter of composition. Why not create a factory function. For example:

function routeHandlerWithAppHeader(Component) {
  return (props) => (
    <div>
      <AppHeaderMain />
      <Component {...props}/>
    </div>;
  );
}

And then use:

<Route exact path="/" component={routeHandlerWithAppHeader(Home)} />
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, It works, but still I have to repeat this function with another AppHeaderSub, maybe pass the parameter from {this.routeHandlerWithAppHeader(About, Sub)} to AppHeader e.g. <AppHeader page={sub}>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.