How to dynamically add component in reactjs? Code Example & Demo

Total
0
Shares
How to dynamically add component in reactjs - Code Demo

(Jump to Code | Demo) One of the most important feature of Reactjs is its modularity. To make code more readable and maintainable, we break it into reusable components. And most of the times we need to dynamically add these components into scripts.

First of all let’s understand the difference between static component and dynamic component. Static components are included at the compile time while dynamic components are included at run time.

Syntax to add dynamic component

const DynamicComponent = React.lazy(() => import('./DynamicComponent'));

You may also like –

You may use other techniques to create a component at run time. React has createElement function which can be used to create elements as well as complete components. But this approach is messy and hard to maintain. The best way is to create component using JSX and lazy load it when required.

Code Example to dynamically add component

In this example we will create two components –

  1. DynamicComponent – We will render this lazily. The content is the list of famous dialogues of Chandler Bing of friends.
  2. App – This is the landing page where we are going to dynamically add our component.

First, let’s code our DynamicComponent

import React from "react";

export default function DynamicComponent() {
  const dialogues = [
    "https://img.buzzfeed.com/buzzfeed-static/static/2017-04/10/15/asset/buzzfeed-prod-fastlane-02/sub-buzz-15945-1491851513-1.jpg?downsize=700%3A%2A&output-quality=auto&output-format=auto",
    "https://img.buzzfeed.com/buzzfeed-static/static/2017-04/10/14/asset/buzzfeed-prod-fastlane-02/sub-buzz-1319-1491847398-5.jpg?downsize=700%3A%2A&output-quality=auto&output-format=auto",
    "https://img.buzzfeed.com/buzzfeed-static/static/2017-04/10/14/asset/buzzfeed-prod-fastlane-03/sub-buzz-31032-1491847942-7.png?downsize=600:*&output-format=auto&output-quality=auto",
    "https://img.buzzfeed.com/buzzfeed-static/static/2017-04/7/17/asset/buzzfeed-prod-fastlane-03/sub-buzz-3883-1491601994-2.png?downsize=600:*&output-format=auto&output-quality=auto",
    "https://img.buzzfeed.com/buzzfeed-static/static/2017-04/7/17/asset/buzzfeed-prod-fastlane-01/sub-buzz-6195-1491600854-3.jpg?downsize=600:*&output-format=auto&output-quality=auto",
    "https://img.buzzfeed.com/buzzfeed-static/static/2017-04/7/17/asset/buzzfeed-prod-fastlane-02/sub-buzz-6511-1491600854-1.jpg?downsize=600:*&output-format=auto&output-quality=auto",
    "https://img.buzzfeed.com/buzzfeed-static/static/2017-04/10/14/asset/buzzfeed-prod-fastlane-01/sub-buzz-13904-1491848722-3.jpg?downsize=600:*&output-format=auto&output-quality=auto",
    "https://img.buzzfeed.com/buzzfeed-static/static/2017-04/10/14/asset/buzzfeed-prod-fastlane-02/sub-buzz-2221-1491848430-3.png?downsize=600:*&output-format=auto&output-quality=auto",
    "https://img.buzzfeed.com/buzzfeed-static/static/2017-04/10/14/asset/buzzfeed-prod-fastlane-01/sub-buzz-13857-1491848582-1.jpg?downsize=600:*&output-format=auto&output-quality=auto",
    "https://img.buzzfeed.com/buzzfeed-static/static/2017-04/10/15/asset/buzzfeed-prod-fastlane-03/sub-buzz-6359-1491850978-7.jpg?downsize=600:*&output-format=auto&output-quality=auto"
  ];

  return dialogues.map((element, index) => {
    return (
      <div
        key={index}
        style={{ marginBottom: 20, border: "1px solid #000", padding: 5 }}
      >
        <img src={element} style={{ width: "100%", maxWidth: "400px" }} />
      </div>
    );
  });
}

This component will display a list of memes of world famous Chandler Bing. We created an array to store all the image urls. In return function, we are running a loop over this array and displaying images.

Now check out the code of our landing page (App) and how we are dynamically adding our component –

import React, { Suspense } from "react";
const DynamicComponent = React.lazy(() => import("./DynamicComponent"));

export default function App() {
  const [loadDynamicComp, setLoadDynamicComp] = React.useState(0);

  return (
    <div>
      <p>Click button to load dynamic component</p>
      <button onClick={() => setLoadDynamicComp(1)}>
        Load Dynamic Component
      </button>
      {loadDynamicComp ? (
        <Suspense fallback={<div>Loading Component....</div>}>
          <DynamicComponent />
        </Suspense>
      ) : null}
    </div>
  );
}

    Tweet this to help others

You can see that adding a dynamic component is a two way process. First we import it using React.lazy(). Then we wrap it in a wrapper component, Suspense. It has one prop, fallback, which renders anything inside it till DynamicComponent is loading.

Live Demo

Open Live Demo

Learn more about reactjs –