this is undefined for React components
See original GitHub issueI have a jsx file which is roughly the following:
let React = require('react');
module.exports = React.createClass({
getInitialState: () => { username: 'John Doe' },
render: () => {
return (<div>{this.state.username}</div>);
}
});
When I browserify my code, the outcome is:
var React = require('react');
module.exports = React.createClass({
getInitialState: function() {
return { username: 'John Doe' };
},
render: function() {
return React.createElement('div', null, undefined.state.username);
}
});
Notice the undefined.state.username
bit. Any idea where it comes from?
Thanks 😃
Issue Analytics
- State:
- Created 9 years ago
- Comments:11 (3 by maintainers)
Top Results From Across the Web
React: "this" is undefined inside a component function
I want to update loopActive state on toggle, but this object is undefined in the handler. According to the tutorial doc, I this...
Read more >TypeError! How to deal with the undefined “this” in your React ...
It usually appears to refer to an instance of the class, but… Consider this component: When the button is clicked, you get:.
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 >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 >React 18 allows components to render 'undefined'
Until React 18, if a component rendered undefined , React would throw an error at runtime. //Shape.jsx import React from 'react'; ...
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 FreeTop 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
Top GitHub Comments
You can also use the method shorthand syntax inside object literals like so:
@IngwiePhoenix That’s being done by babel-plugin-transform-es2015-modules-commonjs. It’s part of babel-preset-es2015. You can turn off transforming the top level
this
toundefined
by passing it{allowTopLevelThis: true}
. Like this:That of course means that you can’t use a preset, you’ll have to specify the transforms individually so you can pass in that option.