Why React Function Component's this is undefined
Function components can be written using both arrow functions () => {}
like shown in the above question, or as regular function expressions/declarations such as function Foo() {}
. To understand why the above behavior occurs, it is important to first understand that React components are (often) written within ES6 modules.
Why is this
undefined
in an arrow function component?
One of the properties of modules is that this
at the top "module scope" level is undefined
. This behavior differs from regular scripts:
<!-- A "module" is what react component code is usually written in -->
<script type="module">
console.log("Module code (react code) this:", this); // undefined
// ^
const App = () => { // example component |
this // --- taken from surrounding scope ---+
}
</script>
React: this is undefined inside a component function
ES6 React.Component
doesn't auto bind methods to itself. You need to bind them yourself in constructor
. Like this:
constructor (props){
super(props);
this.state = {
loopActive: false,
shuffleActive: false,
};
this.onToggleLoop = this.onToggleLoop.bind(this);
}
this undefined in arrow function
I found the problem. It was my version of NextJS. If I downgrade it to an earlier version, everything works fine. No idea why it breaks in the new version.
Working version: "next": "^11.1.3"
Why this is undefined in React?
You have a few things wrong here. When using a class component along with event methods, you should define state in a constructor. Then bind any methods to the proper context. Try this:
class Transfer extends Component{
constructor(props) {
super(props);
this.state = {
address : '',
amount : ''
};
this.onSubmit = this.onSubmit.bind(this);
}
async onSubmit (event) {
event.preventDefault();
const accounts = await web3.eth.getAccounts();
console.log(accounts);
console.log(this.state);//Why this is undefined?
/*console.log(this.state.address);
await token.methods.transfer(this.state.address,this.state.amount).send({
from:accounts[0]
});*/
}
React Class Component setState undefined
- You do not need the global variable
response
. - No need for the
componentDidMount
either, you already set the initial state in the constructor. setState
is a function, so you need to call it and not assign something to it- use an arrow function for the
autoResponse
, if you intend to pass it as a prop to other components, so that it retains the correctthis
.
import React, {
Component
} from "react";
class Track extends Component {
constructor(props) {
super(props);
//Setting the initial state
this.state = {
response: ""
};
}
autoResponse = () => {
this.setState({
response: "This is not a valid tracking #"
});
}
render() {
return (<>
<input placeholder="Enter Tracking #"></input>
<button onClick={this.autoResponse}>TRACK</button>
<div className="response-cntr">
<p className="response-text">{this.state.response}</p>
</div>
</>);
}
}
export default Track;
React: Passing value to a functional component results in undefined value
The parameter passed to a function component is the props
object which contains the passed props, so you just need to grab props.room
from there:
function Room(props){
console.log(props.room.name)
return(
<div>
<h1>Room name: {props.room.name}.</h1>
</div>
)
}
Or, with object destructuring:
function Room({ room }){
console.log(room.name)
return(
<div>
<h1>Room name: {room.name}.</h1>
</div>
)
}
Related Topics
Create a Date With a Set Timezone Without Using a String Representation
Delete Firebase Data Older Than 2 Hours
Queryselector and Queryselectorall VS Getelementsbyclassname and Getelementbyid in JavaScript
How to Use Webpack to Generate CSS and Js Separately
Change Text on Hover, Then Return to the Previous Text
Open a File with Default Program in Node-Webkit
Change Type of Input Field with Jquery
Jqgrid Server Side Error Message/Validation Handling
How to Check If File Exists in Jquery or Pure JavaScript
How to Write a Countdown Timer in JavaScript
How Does This Object Method Definition Work Without the "Function" Keyword
Converting Between Strings and Arraybuffers
Using JavaScript to Edit CSS Gradient
Can You Have a JavaScript Hook Trigger After a Dom Element's Style Object Changes