redmaster
redmaster

Reputation: 145

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>
  )
}

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>
    )
  }
}

Upvotes: 0

Views: 319

Answers (1)

Bilal Nasir
Bilal Nasir

Reputation: 250

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>
    )
  }
}

Upvotes: 2

Related Questions