2

I tried to dynamically pass a reference to a class to a container and render it.

    class Test extends React.Component{
        render() {
           return <div>Test</div>
        }
    }

    class HelloWidget extends React.Component{
           constructor(props) {
              super(props);

              this.state = {
                  child: Test
              };
           }

           render() {
               return <div>{this.state.child}</div>;
          }
    }

    React.render(<HelloWidget />, document.getElementById('container'));

See it at jsfiddle: https://jsfiddle.net/coolshare/jwm6k66c/2720/

It did not render anything...

Any suggestion?

thanks

3 Answers 3

2

You can dynamically change the state value in HelloWidget component and that would reflect in Test Component. Here is the code:

    class Test extends React.Component{

            render() {
        return <div>{this.props.child}</div>
    }
        }
  class HelloWidget extends React.Component{
    constructor(props) {
      super(props);

      this.state = {
            child: "Test"
      };
    }

    render() {
        return <div>
            <Test child={this.state.child}/>
        </div>;
    }
  }

  React.render(<HelloWidget />, document.getElementById('container')); 

Here is a working fiddle link: https://jsfiddle.net/jayesh24/1uvpg5ej/

Sign up to request clarification or add additional context in comments.

Comments

1

You need to use React.createElement to create the new react element.

Like this:

render() {
    return <div>hello {React.createElement(this.state.child)}</div>;
}

Check the working fiddle.

1 Comment

@MarkQian If you find the answer useful please mark it as correct.
0

Use the Directive of your Test inside the constructor to create that component when you are assigning

      this.state = {
            child: <Test />
      };

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.