AnKing
AnKing

Reputation: 2174

React fails to compile / function undefined

I'm pretty new to react, in one of my components i have the following:

checkNav() {
        if (this.state.step === 0) {
            this.setState({ nextEnabled: this.state.agreementAccepted });
        } else if (this.state.step === 1) {
            this.setState({ nextEnabled: this.state.privacyPolicyAccepted });
        }
    }

    render() {
>173        checkNav();

        return (
            <div className="first-login-form-content">
                <div className="label">Initial Login Wizard</div>
                {this.initialLoginWizard()}
                <div className="navButtons">
                    <button disabled={!this.state.backEnabled} onClick={this.handleBack}>Back</button>
                    <button disabled={!this.state.nextEnabled} onClick={this.handleNext}>Next</button>
                    <button className="acceptBtn" disabled={!this.state.acceptEnabled} onClick={this.handleAccept}>Accept</button>
                </div>
            </div>
        );
    }

But this produces the following error for me:

Failed to compile ./src/components/Login.js Line 173: 'checkNav' is not defined no-undef

Search for the keywords to learn more about each error.

what do i need to do so this function gets declared before being called?

Upvotes: 1

Views: 380

Answers (1)

Sagiv b.g
Sagiv b.g

Reputation: 31014

When you want to run a method of the class's instance you need to access it via the this key word:

this.checkNav()

With that being said, you are calling setState inside the render method which may lead to an infinite loop. Try moving it to another life-cycle method (componentDidUpdate?)

As per the docs:

The render() function should be pure, meaning that it does not modify component state, it returns the same result each time it’s invoked, and it does not directly interact with the browser.

If you need to interact with the browser, perform your work in componentDidMount() or the other lifecycle methods instead. Keeping render() pure makes components easier to think about.

Upvotes: 1

Related Questions