call react component-element as variable

Viewed 462

Is it possible to call a React component element with a variable inside?

    import React from "react"

    /*React functional component*/

    function someName() {

      const someVar = "componentName"; //the name of the called component

      return(
        <{someVar}/>
      )
    }

    export default someName;

I try to implement this in a router and to change the filenames(Sites) (in the element) dynamically with useState from fetched data.

I am open to all kind of help :)

1 Answers

There is no direct way to do that but you can use this approach.

import ComponentA from '...path';
import ComponentB from '...path';
...

const components = {
  componentA: ComponentA,
  componentB: ComponentB,
  ...
}

...
function App(props) {
    const TargetComponent = components[props.componentName];
    return <TargetComponent />;
}
Related