Skip to content

Latest commit

 

History

History
30 lines (24 loc) · 777 Bytes

30.component-switch.md

File metadata and controls

30 lines (24 loc) · 777 Bytes

The switching component

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

Use an object to map prop values to components

import HomePage from './HomePage.jsx';
import AboutPage from './AboutPage.jsx';
import UserPage from './UserPage.jsx';
import FourOhFourPage from './FourOhFourPage.jsx';

const PAGES = {
  home: HomePage,
  about: AboutPage,
  user: UserPage
};

const Page = (props) => {
  const Handler = PAGES[props.page] || FourOhFourPage;

  return <Handler {...props} />
};

// The keys of the PAGES object can be used in the prop types to catch dev-time errors.
Page.propTypes = {
  page: PropTypes.oneOf(Object.keys(PAGES)).isRequired
};

Related links: