myTest532 myTest532
myTest532 myTest532

Reputation: 2381

React make component more reusable

I create a Header and styles for my project and every page will share these components.

The structure is:

<MuiThemeProvider theme={theme}>
    <div className="app-horizontal collapsed-sidebar">
        {/* SideBar Here */}
        <div className="app-container">
            <div className="rct-page-wrapper">
                <div className="rct-app-content">
                    <Header />
                </div>
                <div className="rct-page">
                    <HorizontalMenu />
                    <Scrollbars
                        className="rct-scroll"
                        autoHide
                        autoHideDuration={100}
                        style={getScrollBarStyle()}
                    >
                        <Content />
                    </Scrollbars>
                </div>
            </div>
        </div>
    </div>
</MuiThemeProvider>

Basically I have:

As you can see, for every page that my project navigate to, I'm repeating the same structure of the code above, but changing the <Content />. I believe it not a good approach. Is there a way to make my code more reusable?

Thanks

Upvotes: 0

Views: 524

Answers (1)

lawrence-witt
lawrence-witt

Reputation: 9354

I misread your example code and thought it was the header component itself. Actually, what you probably need is just to change the location of your switch.

If the sample you shared is genuinely the same for every single page of your application, then it is really better to think of it as the application root:

<MuiThemeProvider theme={theme}>
    <div className="app-horizontal collapsed-sidebar">
        {/* SideBar Here */}
        <div className="app-container">
            <div className="rct-page-wrapper">
                <div className="rct-app-content">
                    <Header />
                </div>
                <div className="rct-page">
                    <HorizontalMenu />
                    <Scrollbars
                        className="rct-scroll"
                        autoHide
                        autoHideDuration={100}
                        style={getScrollBarStyle()}
                    >
                        <Switch>
                          <Route exact path="/" component={HomeContent}/>
                          <Route exact path="/users" component={UsersContent}/>
                          ...
                        </Switch>
                    </Scrollbars>
                </div>
            </div>
        </div>
    </div>
</MuiThemeProvider>

I don't know what Navigation.js does in your original code. If it is a component with side-effects or other behaviours you don't want polluting the root component, you could just put it in place of the switch above.

Upvotes: 3

Related Questions