Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to load React Component by variable?

I have multiple components exported in a file ‘buildings.js’
For the sake of simplicity I’ll just give a basic example

export const NewBuilding = () => {
return (
    <div className="wrapper">New Building</div>
)

}

export const Barracks = () => {
return (
    <div className="wrapper">Barracks</div>
)

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Another component get the specific building component name by props. I need to render the building whose name matches the name in the props.

class BuildingContent extends React.Component {
getComponent = () => {
    var name = this.props.content.name;
// Here I want to access the component by variable
// Like <Buildings[name] /> or anything similar that works. 
// This obviously doesn't work
    //return <Buildings.Name /> 

    return <Buildings.Barracks />
}
    render() {
    return (
        <div className='building-content-wrapper'>
// Hardcoded for functionality
            <Buildings.NewBuilding />
        </div>
    )
  }
}

>Solution :

You can create an object of multiple Components and its key should be the name you are passing in props like

const allComponents={
      newBuilding:NewBuilding,
      barracks:Barracks
    }
    
class BuildingContent extends React.Component {
            let name = this.props.content.name;
            let Building=allComponents[name]
        
            render() {
            return (
                <div className='building-content-wrapper'>
                  <Building/>
                </div>
            )
          }
        }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading