mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 07:08:01 +00:00
Add Defining State In A Simple Class Component as a react til
This commit is contained in:
@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
|
||||
For a steady stream of TILs from a variety of rocketeers, checkout
|
||||
[til.hashrocket.com](https://til.hashrocket.com/).
|
||||
|
||||
_603 TILs and counting..._
|
||||
_604 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -422,6 +422,7 @@ _603 TILs and counting..._
|
||||
|
||||
- [Accessing Env Vars In create-react-app](react/accessing-env-vars-in-create-react-app.md)
|
||||
- [create-react-app Comes With Lodash](react/create-react-app-comes-with-lodash.md)
|
||||
- [Defining State In A Simple Class Component](react/defining-state-in-a-simple-class-component.md)
|
||||
- [Dispatch Anywhere With Redux](react/dispatch-anywhere-with-redux.md)
|
||||
- [Force A Component To Only Have One Child](react/force-a-component-to-only-have-one-child.md)
|
||||
- [Inactive And Active Component Styles With Radium](react/inactive-and-active-component-styles-with-radium.md)
|
||||
|
||||
50
react/defining-state-in-a-simple-class-component.md
Normal file
50
react/defining-state-in-a-simple-class-component.md
Normal file
@@ -0,0 +1,50 @@
|
||||
# Defining State In A Simple Class Component
|
||||
|
||||
Most class components start off with a constructor which does some
|
||||
initialization of the component including setting the components initial
|
||||
state. It might look something like the following:
|
||||
|
||||
```javascript
|
||||
class MyComponent extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
loading: true
|
||||
};
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.loading) {
|
||||
return (
|
||||
<p>Loading...</p>
|
||||
);
|
||||
} else {
|
||||
// ...
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If setting state is the only thing you need to do in the constructor,
|
||||
then you can skip the constructor all together.
|
||||
|
||||
```javascript
|
||||
class MyComponent extends React.Component {
|
||||
state = {
|
||||
loading: true
|
||||
};
|
||||
|
||||
render() {
|
||||
if (this.state.loading) {
|
||||
return (
|
||||
<p>Loading...</p>
|
||||
);
|
||||
} else {
|
||||
// ...
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This second example will work the same as the first, and it is a bit more
|
||||
concise.
|
||||
Reference in New Issue
Block a user