React-Router: How to render different components on different parts of the page with one route

dens14345 Source

I have 2 links in my sidebar, this will change the link to "inbox" and "contacts" my problem is that when the route changes, the content of the sidebar doesn't change and I need to reload the page to render the content of it.

the links on the sidebar will append an ID and it can render perfectly the for example, the contact that has that ID in the route.

enter image description here

class App extends Component {
    render() {
        return (
            <Router>
            <div>
                <SidebarContainer/>

                <Route exact path="/inbox/:id" component={MessageContainer}/>
                <Route  path="/contacts" component={ContactContainer}/>
                <Route  path="/test" component={Test}/>

            </div>
        </Router>
    )
}
}

Here's what I tried in the Component

render() {
    return (
        <div>
                <li className="padded-left">
                    <div>
                        <Link onClick={this._showInbox} to="/inbox" className="waves-effect waves-teal btn-flat">
                            <i className="material-icons">chat</i>
                        </Link>

                        <Link onClick={this._showContacts} to="/contacts" className="waves-effect waves-teal btn-flat">
                            <i className="material-icons">contacts</i>
                        </Link>
                    </div>

                </li>

                <li>
                    <Link to="/test" className="waves-effect waves-teal btn-flat">
                        <i className="material-icons">Test</i>
                    </Link>
                </li>

                <li>
                    <div className="divider">_</div>
                </li>

                <Route path="/inbox" component={ConversationContainer}/>
                <Route path="/contacts" component={ContactsContainer}/>
            </ul>



        </div>
    );
}

enter image description here

reactjsreact-router

Answers

answered 6 months ago Tim Givois #1

In this case, I won't render the SideBarContainer inside the Router. You have to take into account that, when you navigate, the only thing that will be triggered to be rendered is the component inside the Route. Your Sidebar will always stay the same unless you refresh the page (here, the whole App is triggered to be rendered again)

As you are expecting the SideBar to change given a specific Route, you should render it inside the components of <Route /> .

comments powered by Disqus