Alon Joshua
Alon Joshua

Reputation: 75

Function is undefined in a class component react

I transfered the function from render method to be inside the class and I get ('btnClick' is not defined no-undef) on my function, I don't understand why.

class Generator extends React.Component {
    constructor (props) {
        super(props)
        this.state = { 
        onView: '0',
        minNum: 0 ,
        maxNum: 100
      } 
    }

    btnClick = () => {
      const { minNum, maxNum } = this.state;
      console.log(minNum);
     };

  render() {

  return (
    <div className="container">
    <Instructions />
    <Range 
      max={this.state.maxNum} 
      min={this.state.minNum} 
      />
    <Generate currentClick={btnClick}/>
    <View show={this.state.onView}/>
    </div>
    );
  }
}

export default Generator;

Upvotes: 0

Views: 49

Answers (4)

SanjiMika
SanjiMika

Reputation: 2714

You must write

 <Generate currentClick={this.btnClick}/>

Bonus : For the declaration of functions in class component React, you used the arrow function here, it's good for the shared context "this" of class.

btnClick = () => {
//...
}

Upvotes: 0

Sophia Lee
Sophia Lee

Reputation: 37

try <Generate currentClick={this.btnClick}/> mistyped 'this'

Upvotes: 1

TBouder
TBouder

Reputation: 2719

Inside a React.Component class, you have to use this to refers to internal functions (or methods).

In your case, you should do <Generate currentClick={this.btnClick} /> or <Generate currentClick={() => this.btnClick()} />

Upvotes: 1

mdev
mdev

Reputation: 359

you forgot. the this.

Do this this.btnClick

Upvotes: 1

Related Questions