The switching component

A switching component is a component that renders one of many components.

Use an object to map prop values to components

  1. import HomePage from './HomePage.jsx';
  2. import AboutPage from './AboutPage.jsx';
  3. import UserPage from './UserPage.jsx';
  4. import FourOhFourPage from './FourOhFourPage.jsx';
  5. const PAGES = {
  6. home: HomePage,
  7. about: AboutPage,
  8. user: UserPage
  9. };
  10. const Page = (props) => {
  11. const Handler = PAGES[props.page] || FourOhFourPage;
  12. return <Handler {...props} />
  13. };
  14. // The keys of the PAGES object can be used in the prop types to catch dev-time errors.
  15. Page.propTypes = {
  16. page: PropTypes.oneOf(Object.keys(PAGES)).isRequired
  17. };