'this' becomes undefined when called from onClick inside a class that extends React.Component
See original GitHub issueI have something similar to this code snippet:
class MyButton extends Component {
state = { tapped: false }
tap() {
this.setState({ tapped: true }); // --> 'this' here is undefined
}
render() {
return (
<button onClick={ this.tap }>TAP ME</button>
)
}
}
As the comment above specifies, when the tap() method got called from the button’s onclick, I got an error that basically told me that ‘this’ is undefined.
This error will be gone if I declare this class using React.createClass. Is this intentional? Thank you in advance!
Issue Analytics
- State:
- Created 8 years ago
- Comments:5 (1 by maintainers)
Top Results From Across the Web
React: "this" is undefined inside a component function
export default class SignupPage extends React.Component { constructor(props) { super(props); } handleSubmit(e) { e.preventDefault(); const data = { email: ...
Read more >Solved: REACT: this undefined in button click
Now, I have a button which calls a function within its same class: onRenderFooterContent() { return ( <div> <PrimaryButton onClick={() => this.
Read more >Deal with Undefined 'this' in React Event Handlers Correctly
When teaching React to developers, one thing that comes up often is dealing with a common error. In this post, learn how to...
Read more >How To Fix Undefined 'this.state' in React Class Components
If you're working with React class components, you may find yourself vexed by 'this.state' being undefined.
Read more >The 10 Most Common JavaScript Issues Developers Face
The outer function returns the inner function (which also uses this scoped num variable) and the element's onclick is set to that inner...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
React.createClass
auto bindthis
for you behind the scene.In ES6 classes, you should bind this yourself:
<button onClick={this.tap.bind(this)}>
Just for info, it can also be solved as below,