I'm just starting to learn React.js (and Javascript) and I have a very basic question for you guys.
This is a working example of a small component that creates 3 buttons for which a value is incremented each time they are clicked.
class Button extends React.Component {
handleClick = () => {
this.props.onClickFunction(this.props.incrementValue);
}
render(){
return(
<button onClick={this.handleClick}>
{this.props.incrementValue}
</button>
);
}
}
const Result = (props) => {
return(
<div>{props.counter}</div>
);
};
class App extends React.Component {
state = {counter: 0};
incrementCounter = (incrementValue) => {
this.setState((prevState) => ({
counter: prevState.counter + incrementValue
}));
};
render() {
return (
<div>
<Button incrementValue={2} onClickFunction={this.incrementCounter}/>
<Button incrementValue={10} onClickFunction={this.incrementCounter}/>
<Button incrementValue={99} onClickFunction={this.incrementCounter}/>
<Result counter={this.state.counter}/>
</div>
);
}
}
ReactDOM.render(<App />, mountNode);
While experiencing with the code, I tried to change the handleClick function.
class Button extends React.Component {
handleClick(){
this.props.onClickFunction(this.props.incrementValue);
}
render(){
return(
<button onClick={this.handleClick}>
{this.props.incrementValue}
</button>
);
}
}
const Result = (props) => {
return(
<div>{props.counter}</div>
);
};
class App extends React.Component {
state = {counter: 0};
incrementCounter = (incrementValue) => {
this.setState((prevState) => ({
counter: prevState.counter + incrementValue
}));
};
render() {
return (
<div>
<Button incrementValue={2} onClickFunction={this.incrementCounter}/>
<Button incrementValue={10} onClickFunction={this.incrementCounter}/>
<Button incrementValue={99} onClickFunction={this.incrementCounter}/>
<Result counter={this.state.counter}/>
</div>
);
}
}
ReactDOM.render(<App />, mountNode);
I am now getting: Uncaught TypeError: Cannot read property 'props' of undefined at handleClick (eval at
From my understanding, the anonymous function handleClick = () =>... can access the props from the parent because of a closure but why does the magic stop when I replace it with a class method?