2

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?

1 Answer 1

5

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>
    );
}
Sign up to request clarification or add additional context in comments.

1 Comment

JSX is supported with tsx files and your suggestions works great, thanks!

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.