DEV Community

Ayomikun Sholademi
Ayomikun Sholademi

Posted on

Dynamic Components in React

Introduction

Hi there, if you have worked with Vue, you would realise you are able to use components dynamically through the component tag as shown below

<script>
import CustomComponent from 'path-to-custom-component'
import AnotherComponent from 'path-to-another-component'

export default {
  components: {CustomComponent, AnotherComponent},

  data() {
    return {
      activeComponent: 'CustomComponent'
    }
  }
}
</script>

<template>
  <div>
   <component :is="activeComponent" />
  </div>
</template>

Enter fullscreen mode Exit fullscreen mode

In this article, I would be demonstrating a way how you can use components dynamically in React.

lets start coding

I'm going to assume you already have a react project set up so I'm going to jump right into it

First, create a components folder in the root directory if you do not have one yet.
Inside the components folder, create a new file named DynamicComponent.js and add the following code:

import React from "react";

/**
 * @desc the dynamic component is used to render various component dynamically
 * @params props: {
 *    useDefaultPath: this indicates that the component to be used is in the components folder if set to true else you would have to pass in a different component
 *    is: if `useDefaultPath` is true, you pass in the name of the component file or the path to the component in the component folder eg: NewComponent or BaseUI/NewComponent
 *    ...rest: the props to be passed into the new component
 * }
 */
const DynamicComponent = ({ is, useDefaultPath = true, ...rest }) => {
  return React.createElement(
    useDefaultPath ? require(`./${is}.js`).default : is,
    {
      ...rest,
    }
  );
};

export default DynamicComponent;

Enter fullscreen mode Exit fullscreen mode

We can now use this component in other files to dynamically render different components based on conditions we have set.

Example would be this code below

import "./App.css";
import DynamicComponent from "./components/DynamicComponent";
import { useState } from "react";

function App() {
  const [activeComponent, setActiveComponent] = useState("SayHello");
  return (
    <div className="App">
      <header className="App-header">
        <DynamicComponent is={activeComponent} name="Sholademi Ayomikun" />

        <button
          onClick={() =>
            // Note that `SayHello` and `SayGoodbye` have been defined in the components folder
            setActiveComponent(
              activeComponent === "SayHello" ? "SayGoodbye" : "SayHello"
            )
          }
        >
          Toggle Component
        </button>
      </header>
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Conclusion

The article shows how you can use React.createElement to dynamically render components. The code for this can be found here.
Use cases would be to dynamically change app layout or have multiple tabs with different view.
Please note that there are several approaches to doing this in React.

Follow me on twitter and github

Also subscribe to my youtube channel. I'm trying to get up to 50 subscribers to start dishing out content there.

Top comments (1)

Collapse
 
awaisalwaisy profile image
Alwaisy al-waisy

how to use it with tsxf file.