2

I want a component which renders on every route, and has child components (e.g. a header).

By leaving out exact in the route I can achieve that.

render(
    <Router>
      <Route path="/" component={App}/>
    </Router>,
    document.getElementById('app')
);

Inside the component, I have nested routes:

const App = ({match}) => (
    <Switch>
      <Route path={`${match.url}login`} component={LoginForm}/>
      <Route path={`${match.url}panel`} component={ControlPanel}/>
    </Switch>
);

It picks one out of two components to render, based on the path.

As shown in the documentation we need to use the match url. This was very confusing to me, since the match.url is /, and blindly following the examples I wrote e.g. '{${match.url}/login}', which results in //login `

My question: if I do not match a parameter, why can't I use a full path in the child?

The following does not work when used inside App:

<Route path="/login" component={LoginForm}/>
6
  • I use ver3 but the way I setup my router should apply to your case. If you want to render a component on every route you don't need to provide a path. Do something like this: <Route component={NavPanel}> Commented May 3, 2017 at 15:59
  • Inside of NavPanel you refer to nested components as props.children. This way all your router logic can be placed in one place. I can give a more complete answer if you so require. Commented May 3, 2017 at 16:02
  • Thanks! That solves my problem, but does not answer my question :) Commented May 4, 2017 at 7:04
  • I dont quite understand what the question is. Are you saying that using path={${match.url}login} is equivalent to path="/login" but the latter does not work? Commented May 4, 2017 at 8:13
  • Almost. Is does work, but not when nested. Commented May 4, 2017 at 12:19

1 Answer 1

1

I am not sure that I understand you correctly. I think you should use path instead of url.

const App = ({match}) => (
    <Switch>
      <Route path={`${match.path}/login`} component={LoginForm}/>
      <Route path={`${match.path}/panel`} component={ControlPanel}/>
    </Switch>
);
Sign up to request clarification or add additional context in comments.

Comments

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.