Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep Sidebar with React Router

I want to switch Detail and Blog but still keep Sidebar. I use like this code below but it does not work. Can you help me to correct it? Thank you so much.

const routes = (
        <Switch component={App}>
                <Route exact key="detailpost" path={CelestialSettings.path + 'posts/:slug'} 
                        components={{main: Detail, sidebar: Popular, mainbottom: Categories}} />) } 
                        />
                <Route exact key="listpost" path={CelestialSettings.path} 
                    components={{feature:Featurex, main: Blog, sidebar: Popular, mainbottom: Categories}} />) } 
                    />
        </Switch>
 );

 class App extends React.Component {
    render () {
        const {feature, main, sidebar, mainbottom } = this.props;
        return (
            <div>
                <div className="container">
                    <div className="main-feature" id="main-feature">
                        {feature}
                    </div>
                </div>
                <div id="content" className="site-content">
                    <div className="container">
                        <div className="divcontainer">
                            <div id="po-homepage" className="content-area">
                                {main}
                            </div>
                            <aside id="secondary" className="sidebar widget-area">
                                <div className="popular_post" id="popular_post">
                                    {sidebar}
                                </div>
                            </aside>
                        </div>
                    </div>
                </div>
                <div className="cat-list">
                    <div className="container">
                        <div className="thecategories" id="thecategories">
                            {mainbottom}
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}

ReactDOM.render( 
    (routes),
    document.getElementById('app')
);
like image 693
Hai Tien Avatar asked Mar 06 '23 01:03

Hai Tien


1 Answers

To keep the same Sidebar among multiple routes you can put your Sidebar component on the same level as Switch component. Rough example:

const routes = (
    <div>
        <YourSidebar>
            {/* ... */}
        </YourSidebar>
        <Switch component={App}>
            <Route ... />
            <Route ... />
            {/* ... */}
        </Switch>
    </div>
);

This way, React-Router will not re-render (or update) the sidebar component, and only control contents of a <Switch>.

like image 138
ilonacodes Avatar answered Mar 23 '23 14:03

ilonacodes