0

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

1 Answer 1

2

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