I have created the below class
class App extends Component{
render() {
return (
<div className="app"></div>
);
}
}
How do i set initial state? getInitialState()
isn't working?
what am i doing wrong?
The react docs are also not helping.
There are two ways to initialize state in a React component: inside the constructor, and directly inside the class.
Initializing state In class components, there are two ways to initialize state — in a constructor function or as a Class property. Constructor functions, introduced in ES6, is the first function called in a class when it is first instantiated — meaning when a new object is created from the class.
To update state , React developers use a special method called setState that is inherited from the base Component class. The setState method can take either an object or a function as the first argument.
To initialize state from props in a React component, we can watch the prop's value with the useEffect hook, then we can call the state setter function to set the state's value to the prop's value. to create the Child component with the text prop. We create the val state with the useState hook.
import React, { Component } from 'react';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
text: 'Hello World'
};
}
render() {
return (
<div>
{this.state.text}
</div>
);
}
}
You may also want to check out this post about the difference between when to use a constructor and when to use getInitialState.
What is the difference between using constructor vs getInitialState in React / React Native?
There is also a shortcut of Jenna's great answer, which doesn't use constructor
or this
:
class App extends Component {
state = {
text: 'Hello World'
};
render() {
return (
<div>
{this.state.text}
</div>
);
}
}
A simplified example shows that the output is the same in both cases:
But if we extend a parent class, the transpiled output does differ, since the number of arguments in the constructor is unknown.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With