1

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 Answer 1

2

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 />;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.