Fzum
Fzum

Reputation: 2055

ReactJS: Fire Method when Component is rendered

I got a general question about ReactJS:

Is it possible to fire a method as soon as all the JSX-Components (<div> components </div>) are successfully rendered? So if some are only rendered on certain conditions could i fire a method as soon as all of them are true.

How would i check if everything got sucessfully rendered?

Upvotes: 1

Views: 1166

Answers (2)

Mayank Shukla
Mayank Shukla

Reputation: 104369

There is a lifecycle method componentDidMount that will get called immediately after react renders the component, it will get called once, only after the initial rendering, i think you can use that method.

As per DOC:

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.

About second ques:

You are rendering the elements on the basis of some conditions, i am assuming that you are using some kind of bool or checking the length of array, so there is a lifecycle method componentWillUpdate, it will get called before the react re-render the component (it will not get called on initial rendering) inside this method you can check for all conditions and call any method if all the conditions are true. So whenever you do setState it will get called and you can put the logic here.

Upvotes: 3

Nitzan Tomer
Nitzan Tomer

Reputation: 164139

This is just a skeleton, but it should help you to get to the solution that you're looking for:

type ChildProps = {
    onUpdated: () => void;
}

class MyChildComponent extends React.component<ChildProps, void> {
    componentDidUpdate() {
        this.props.onUpdated();
    }

    render() {
        ...
    }
}

class MyComponent extends React.Component<void, void> {
    private childCount: number;
    private updated: number;

    constructor() {
        this.childCount = 2;
    }

    render() {
        this.updated = 0;

        return (
            <div>
                <MyChildComponent onUpdated={ this.childUpdated.bind(this) } />
                <MyChildComponent onUpdated={ this.childUpdated.bind(this) } />
            </div>
        );
    }

    private childUpdated() {
        this.updated++;
        if (this.updated === this.childCount) {
            // do something...
        }
    }
}

Upvotes: 1

Related Questions