1.

How to create a switching component for displaying different pages?

Answer»

A SWITCHING component refers to a component that will RENDER one of the multiple components. We should use an object for mapping prop values to components.

A below-given example will show you how to display different PAGES based on page prop using switching component:

import HomePage from './HomePage'import AboutPage from './AboutPage'import FacilitiesPage from './FacilitiesPage'import ContactPage from './ContactPage'import HelpPage from './HelpPage'const PAGES = { home: HomePage, about: AboutPage, facilitiess: FacilitiesPage, contact: ContactPage help: HelpPage}const Page = (props) => { const Handler = PAGES[props.page] || HelpPage return <Handler {...props} />}// The PAGES object keys can be used in the prop TYPES for CATCHING errors during dev-time.Page.propTypes = { page: PropTypes.oneOf(Object.keys(PAGES)).isRequired}


Discussion

No Comment Found