In ES6, is it possible to create local variables and just reference them directly, instead of adding this.
in front, like this.name
.
Example, in the code below, what can I do to make it possible to write {name}
instead of {this.name}
all the time. (Adding this.
in front of variables is a bit cumbersome!)
class User extend React.Component {
name = "Joe";
render() {
// is it possible to write {name} instead of {this.name}
return <div>{name}</div>
}
}
This is possible with with
statement, but since it isn't compatible with strict mode, it has no value in modern JS.
There's no way to do this otherwise, and since this.name
shouldn't be confused with name
variable , omitting this
would be a mistake.
If this.name
in JSX affects readability or is used many times, the property can be destructured:
render() {
const { name } = this;
return <div>{name}</div>
}
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