2

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

(UPDATE) Looking back at it, i realise that what i was actually looking for, was react-router

Filtenborg
  • 377
  • 6
  • 13

3 Answers3

1

for more elegant code you can use a ternary operator:

export default class GameArea extends React.Component {
  render() {
    return (
      <div>
      {
        this.props.newStage === 'News' ? <News/> : <Team/>
      } 
      </div>
    );
  }
};
  • This definantly shortens the code by alot! I will keep this syntax in mind and use it at a later instance of my project :) Andy_D's answer is more what i'm looking for, I do however really appreciate that you took your time to help me :) – Filtenborg Feb 19 '17 at 18:08
0

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.

Community
  • 1
  • 1
Andy_D
  • 4,112
  • 27
  • 19
0

You can create React element manually from the component:

class Hello extends React.Component {
  render() {
    return <div>Hello {this.props.toWhat}</div>;
  }
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(React.createElement(Hello, {toWhat: 'World'}, null));
James Bond
  • 2,229
  • 1
  • 15
  • 26