Blog>
Snippets

Dynamic Import for Component-level Dynamic Routes

Demonstrate how to use dynamic imports to load components based on route parameters, allowing for component-level control over dynamic route rendering.
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

// Placeholder for a component which will render when no route matches
const NoMatch = () => <div>404 - Not found</div>;

// This function dynamically imports a component based on the componentName parameter
function loadComponent(componentName) {
  return React.lazy(() => import(`./components/${componentName}`));
}

// This component uses React Router for routing and dynamic imports for loading components
const App = () => (
  <Router>
    <React.Suspense fallback={<div>Loading...</div>}>
      <Switch>
        {/* Route parameters allow us to get the component name from the URL */}
        <Route path='/:componentName' render={({ match }) => {
          const Component = loadComponent(match.params.componentName);
          return <Component />;
        }} />
        <Route component={NoMatch} />
      </Switch>
    </React.Suspense>
  </Router>
);

export default App;
This code sets up a React application with routing using React Router. It dynamically imports components based on the route parameter 'componentName'. React.lazy is used for dynamic imports and React.Suspense is used for displaying a loading fallback while the component is being loaded. Routes are defined in such a way that an unmatched route will render a '404 - Not found' component.