0

my page.js

class R1 extends React.Component {

    render() {
        return (
            <div className="r1">
                <h1>level1</h1>
            </div>
        );
    }
}
class R2 extends React.Component {
    render() {
        return (
            <div className="r2">
                <h1>level2</h1>
            </div>
        );
    }
}

my main.js

important * as Page from './page';
class App extends React.Component {
    render() {
        return (
            <div className="r1">
                <Page.R+level/>
            </div>
        );
    }
}

Skip getInitialState, I want to dynamic render with level. I try React.renderComponent(<Page.R+this.state.level />, document.body);

It's not working with failed: SyntaxError

Is there more easily way? or is dynamic render available?

thanks

2 Answers 2

1

Not sure how you are exporting your Components so there is an assumption here, generally it is convention to put them in different files.

You can render in your parent component using an if statement inside JSX like this:

class App extends React.Component {
  render() {
    var renderPage;
    if (something) {
      renderPage = <PageOne />;
    } else {
      renderPage = <PageTwo />;
    }
    return (
      <div>
       {renderPage}
      </div>
    );
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

main.js can be modified like this to achieve what you want

import * as Page from './page';
class App extends React.Component {
  render() {
  const level = 2;
    return (
      <div className="r1">

        {/*You use loop over list to get value of level and render all the pages*/}

        {React.createElement(Page[`R${level}`], null)} 

      </div>
    );
  }
}

Page is an object and we are trying to access the pages and rendering the component name which is in string type.

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.