Filtenborg Filtenborg -4 years ago 106
React JSX Question

How to dynamically create and render JSX elements, defined from this.props with react

So I want to create and render a JSX element based on the 'this.props.x', where this 'this.props.x' is the state passed down from app.jsx.

I do have a workaround which works fine, but it is really ugly! Which is why I'm looking for a more elegant way of doing this.

So the way i do it now, is with an if/else like so:

import React from 'react'

import Team from './inMenuTeam.jsx';
import News from './inMenuNews.jsx';

export default class GameArea extends React.Component{
GameStage(page){
if(page == 'News'){
return <News />
}
else{
return <Team />
}
}
render(){
return(
<div>
{this.GameStage(this.props.newStage)}
</div>
);
}
};


What i want to do i something like this:

export default class GameArea extends React.Component{
GameStage(page){
return <page />
}
render(){
return(
<div>
<GameMenuLeft handleMenuClick={this.props.handleMenuClick.bind(this)} />
{this.GameStage(this.props.newGameAreaStage)}
</div>
);
}
};


Where the 'page' element is the prop beeing passed by the parent jsx file.
Above code doesn't work, but doesn't provide me with an error either, so i have a feeling that I'm close to the desired solution.

Thank you :)

Answer Source

There is no page component. A similar way to do it would be:

const pages = {
  News: News,
  Team: Team,
}; // this could also be shorthanded as const pages = { News, Team };

GameStage(page){
  const Page = pages[page];
  return <Page />
}

You can't have dynamic inline component names, see this question for more info.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download