0

Is it possible to route a component from another component?

So normally it would be done like below

<NavLink to="/link">link</NavLink>
<NavLink to="/anotherLink">link </NavLink>
<Switch>
    <Route exact path="/link" component={linkComponent}/>
    <Route path="/anotherLink" component={anotherLinkComponent}/>
</Switch>

but is it possible to have NavLink in one component which is loaded in the main component then route from the main component? So have NavLink in one component and have Route in the main component.

The Nav component

export default class Nav extends Component {
    render() {
        return (
            <nav className="navigation">
                <ul className="nav-container">
                    <li>
                        <NavLink to="/" className="nav-title">
                            First Page
                        </NavLink>
                    </li>
                    <li>
                        <NavLink to="second-page" className="nav-title">
                            Second Page
                        </NavLink>
                    </li>
                    <li>
                        <NavLink to="third-page" className="nav-title">
                            Third Page
                        </NavLink>
                    </li>
                </ul>
                <div className="nav-decoration">

                </div>
            </nav>
        )
    }
}

The App component

import Nav from 'whateverthepath';

export default class App extends Component {

    render() {
        return (
            <div>
                <Nav/>
                <Switch>
                    <Route exact path="/" component={Firstpage}/>
                    <Route path="/secondpage" component={Secondpage}/>

                </Switch>
            </div>
        )
    }
}

All the appropriate React imports are done

forJ
  • 4,309
  • 6
  • 34
  • 60
  • So long as a Route matching a Link's destination is within the visible rendered hierarchy, React Router will render it. Your example should work, you need to wrap the `App` within a `Router` and try it. – hazardous Apr 06 '17 at 06:05

1 Answers1

0

That's definitely possible and your example should even work as is. The biggest thing you'll need to make sure of is that your <Route>s were rendered as some point. The reason your example works is because you're rendering <Nav> in the same render() method as your <Switch> statement. If you were to instead just render <Nav> without ever rendering the switch statement, then the NavLinks would take you somewhere that React Router hasn't been informed about. That's typically why your <Route>s are almost always in your most parent component, to make sure they're rendered.

Tyler McGinnis
  • 34,836
  • 16
  • 72
  • 77