pureofpure
pureofpure

Reputation: 1090

ReactJS and how to reuse shared components

I'm making a web-application with reactJS and mobx and I have some questions on how I should reuse my components and which is the most efficient way. My problem is that I have many components that they share many other same components. For example, I have some pages like ( Home, About, Help, etc..) and they are separate as components and they also respectively contains a Header, Footer and a Content components (from which Header and Footer are stateful components, since the user can change language ), but for my website, each page has the same header and footer, so every page imports and renders the same header and footer. My question is if this is an efficient way, or there is some other way, like to keep header and footer components in some place, and change in some way only the content and not import header and footer every time?

Upvotes: 0

Views: 693

Answers (1)

jaxoncreed
jaxoncreed

Reputation: 1128

You could have a "Layout.jsx" component that has your header and footer and an interchangeable Content component which will switch between Home, About, etc. depending on the route you're in.

If you're already using React Router (Which I highly recommend), you can achieve this by nesting your other routes within a route for layout:

import React from "react";
import {IndexRoute, Route} from 'react-router';
import Layout from "Layout.jsx";
import Home from "Home.jsx";
import Help from "Help.jsx";
import NotFound from "NotFound.jsx";

export default () => {
  return (
    <Route path="/" component={Layout}>
      { /* Home (main) route */ }
      <IndexRoute component={Home}/>

      { /* Routes */ }
      <Route path="about" component={About}/>
      <Route path="help" component={Help}/>

      { /* Catch all route */ }
      <Route path="*" component={NotFound} status={404} />
    </Route>
  )
}

Upvotes: 1

Related Questions