Wim Haanstra
Wim Haanstra

Reputation: 5998

Render React component from instantiated React.Component

I have a couple of React components that are all based of the same base class, these component have a couple of properties which I would like to read before I render the component. This has to do with some conditions that are used somewhere else.

Currently I am calling a method, with something like this in my Render function.

public getWidget(): JSX.Element {

    let widget = null;
    switch (widgetType) {
        case 'widget1': {
            widgetComponent = new Widget1(props); // private variable in my class
            widget = (<Widget1 { ...props } ref = { some-ref });
        }
        case 'widget2': {
            widgetComponent = new Widget2(props); // private variable in my class
            widget = (<Widget2 { ...props } ref = { some-ref });
        }
    }
    return widget;
}

This way I can ask the widget some stuff about it's default values and render the widget variable in my Render function, like this:

render() {
    const widget = this.getWidget();

    const somethingIWantToKnow = this.widgetComponent.someProperty;

    return ({ widget });
}

From what I understand, the reference I set for my React Component is only available after I render? Otherwise I could just use that.

I also tried calling this.widgetComponent.render() in my own Render method, but this does not set up the component correctly (probably because of missing componentWillMount and componentDidMount calls.

I just can't believe this is the way to go, is there a way to render from this.widgetComponent in my Render method, or is there a way to get properties from the class behind a JSX.Element?

NULL checks and other stuff is all removed from these code snippets :)

Upvotes: 0

Views: 139

Answers (1)

Anurag Awasthi
Anurag Awasthi

Reputation: 6223

Give your widget a ref,

widget = (<Widget1 { ...props } ref = { widget1 } />);

Then you can access your instantiated component in componentDidMount and use the ref to access the property,

componentDidMount(){
    const somethingIWantToKnow  = this.widget1.current.someProperty
}

Upvotes: 1

Related Questions