Ravi
Ravi

Reputation: 369

React: Load a component by it's name

It's simple, user types a name of the component in a text-box and I should render it into a div. The component is available in my node-modules folder.

thanks, Ravi

Upvotes: 0

Views: 69

Answers (1)

Eloi
Eloi

Reputation: 108

I think you can do something like that :

import React, { useState } from "react"
// here, import all components that the user could choose (I personnally did it 
// only with Loader

import Loader from "components/common/Loader"

const Test = () => {
  const [userComponent, setUserComponent] = useState(null)
  const [componentName, setComponentName] = useState("")

// here, in componentAssociator, the key must should be the name of the component
// and the value is the component itself
  const componentAssociator = { Loader: Loader }

  const handleComponentChange = (e) => {
    setComponentName(e.target.value)
  }

  const loadComponent = () => {
    setUserComponent(componentAssociator[componentName])
  }

  return (
    <>
      <input value={componentName} onChange={handleComponentChange} />
      <button onClick={loadComponent}>OK</button>
      <div>{userComponent}</div>
    </>
  )
}

export default Test

I hope it'll help you !

Upvotes: 1

Related Questions