Typescript React componentDidMount not getting called

13,605

Don't call your component's render() method yourself. Also, don't instantiate it yourself. Also, pass props in to your component, rather than setting state directly:

Change this:

var main = new MyAppApp.Components.HomePageView("1", result);
main.state = result;
var mainView = main.render();
ReactDOM.render(mainView, document.getElementById(app.templateContainer));

To this:

ReactDOM.render(
    <MyAppApp.Components.HomePageView result={result} />,
    document.getElementById(app.templateContainer)
);

If JSX is not supported, then you can do:

ReactDOM.render(
    React.createElement(MyAppApp.Components.HomePageView, { result: result}),
    document.getElementById(app.templateContainer)
);

Then access results via this.props.result rather than this.state:

public render() {
    return (
        <div>
            {this.props.result.map((item, index) =>
                <div className="MyAppBoxContainer" key={index}>
                    <a href={item.Href}>{item.Title}</a>
                </div>
            )}
        </div>
    );
}
Share:
13,605

Related videos on Youtube

Teoman shipahi
Author by

Teoman shipahi

SOreadytohelp Catching the exceptions.

Updated on September 16, 2022

Comments

  • Teoman shipahi
    Teoman shipahi over 1 year

    I am trying to run some sample with typescript/react, but for some reason componentDidMount function is not getting fired, and I would like to move my AJAX logic in there.

    Here is my code below.

    var app = new MyAppApplication();
    
    namespace MyAppApp.Components {
        // props?: P, context?: any
        export class HomePageView extends React.Component<any, any> {
            constructor(props, context) {
                super(props, context);
                this.state = null;
                // calling here
                console.log("constructor");
            }
            public componentDidMount() {
            // not calling here
                console.log("componentDidMount");
            }
            public render() {
                var view = this.state.map((item, index) =>
                    <div className="MyAppBoxContainer" key={index}>
                        <a href={item.Href}>{item.Title}</a>
                        </div>
                );
                return (<div>{view}</div>);
            }
    
        }
    }
    
    
    app.getHomeContentTitles().then(result => {
        //app.logger.info(this, result);
        var main = new MyAppApp.Components.HomePageView("1", result);
        main.state = result;
        var mainView = main.render();
        ReactDOM.render(mainView, document.getElementById(app.templateContainer));
    }).catch(err => {
        app.logger.error(this, err);
    });
    

    Am I missing something?

  • Teoman shipahi
    Teoman shipahi over 8 years
    JSX is supported with tsx files and your suggestions works great, thanks!