Skip to content

Instantly share code, notes, and snippets.

@darshan09200
Last active March 8, 2021 06:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darshan09200/291f22433c6fcd2c8b9a5808f2803395 to your computer and use it in GitHub Desktop.
Save darshan09200/291f22433c6fcd2c8b9a5808f2803395 to your computer and use it in GitHub Desktop.
This code helps to declare state variable inside and outside the constructor. You can use the state variable anywhere inside the using using this keyword.
class App extends Component {
/**
* Read more about creating constructor here:
* https://reactjs.org/docs/react-component.html#constructor
*/
constructor(props) {
super(props);
this.state = {
key: "value"
};
}
render() {
/**
* Destructuring state object
* Learn more about it here:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#object_destructuring
*/
const { key } = this.state;
return <span>{key}</span>;
}
}
class App extends Component {
state = {
key: "value"
};
render() {
/**
* Destructuring state object
*
* Learn more about it here:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#object_destructuring
*/
const { key } = this.state;
return <span>{key}</span>;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment