Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render a react component from a string name

I want to dynamically render a react component from its string-name. Here is what I have done, but it does not work. Can this be done ? An example would really help.

string_name is the name of the component.

var MyComponent = React.createElement(window[string_name], {});
return (
      <div className="wrapper">
          <div>Hello World</div>
          <MyComponent/>
      </div>
    )
like image 560
Geetanjali Panda Avatar asked Aug 08 '16 07:08

Geetanjali Panda


People also ask

How do I get element by tag name in React?

When the button element is clicked, the click event gets triggered, the value of the tagName property can be used to find out HTML element the source of the event and innerText property can be used to find out text written in that HTML element.

How do I render component dynamically in React?

Dynamic Render Function It uses the activeData variable to determine which component to render. const PropertyEditor = Config[activeData. type]; return (<PropertyEditor codeData={activeData} updateData={onUpdateCodeData} />);

Can a React component return a string?

React component can return only string, it's perfectly valid (and works as OP stated) ... but this use case is not supported. Using components to just return a string is not a good choice. It can be ineffective when you need many translated strings in one component.

How do you pass a string as a prop in React?

To pass a number as props to a component in React, wrap the number in curly braces, e.g. <Child num={42} /> . All props you pass to a component that are not of type string have to be wrapped in curly braces. Copied!


1 Answers

The key bit missing, and I don't know if it's documented anywhere, but you need to use a capital letter for the JSX compiler (?) to recoginise it as a type.

import AllComponents from 'Components';

const FooType = 'Foo';

return (
    <div className="wrapper">
        <div>Hello World</div>
        <AllComponents[FooType] />
    </div>
);

Edit - As per the comments

class Foo extends React.Component {
    render() { 
        return <div>Foo 123</div>; 
    }
};

class Bar extends React.Component {
    render() { 
        return <div>Bar 123</div>; 
    }
};


class App extends React.Component {


  render() {
    const all = {
        'Foo': Foo,
        'Bar': Bar,    
    };

    // For the sake of the demo, just randomly pick one of the two
    // usually this would come from an import, or something similar
    const randomKey = ['Foo', 'Bar'][Math.floor(Math.random() * 2)];

    // The resolved component must begin with a capital letter
    const Type = all[randomKey];


    return (
        <div>
            <Type />
        </div>    
    );
  }

};


ReactDOM.render(<App />, document.getElementById('root')); 

JSBin: http://jsbin.com/noluyu/5/edit?js,output

Edit 2

Our typical apps that render components dynamically, usually have an index.js file at the root of all the components directory, that simple list all possible components:

// index.js
export Breadcrumb                from './breadcrumb/Breadcrumb';
export Checkbox                  from './checkbox/Checkbox';
export Comment                   from './comment/Comment';

Then all you have to do is something like:

import AllComponents from './index.js';

const myType = 'Checkbox';
const Type = AllComponents[myType];

.. later ..
return <div><Type /></div>;
like image 68
Chris Avatar answered Oct 08 '22 14:10

Chris