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 Another…


This content originally appeared on DEV Community and was authored by Ayomikun Sholademi

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>

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;

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;

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.


This content originally appeared on DEV Community and was authored by Ayomikun Sholademi


Print Share Comment Cite Upload Translate Updates
APA

Ayomikun Sholademi | Sciencx (2022-04-09T14:00:54+00:00) Dynamic Components in React. Retrieved from https://www.scien.cx/2022/04/09/dynamic-components-in-react/

MLA
" » Dynamic Components in React." Ayomikun Sholademi | Sciencx - Saturday April 9, 2022, https://www.scien.cx/2022/04/09/dynamic-components-in-react/
HARVARD
Ayomikun Sholademi | Sciencx Saturday April 9, 2022 » Dynamic Components in React., viewed ,<https://www.scien.cx/2022/04/09/dynamic-components-in-react/>
VANCOUVER
Ayomikun Sholademi | Sciencx - » Dynamic Components in React. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/04/09/dynamic-components-in-react/
CHICAGO
" » Dynamic Components in React." Ayomikun Sholademi | Sciencx - Accessed . https://www.scien.cx/2022/04/09/dynamic-components-in-react/
IEEE
" » Dynamic Components in React." Ayomikun Sholademi | Sciencx [Online]. Available: https://www.scien.cx/2022/04/09/dynamic-components-in-react/. [Accessed: ]
rf:citation
» Dynamic Components in React | Ayomikun Sholademi | Sciencx | https://www.scien.cx/2022/04/09/dynamic-components-in-react/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.