In languages like C# it's possible to have a property which is based on other properties. Let us suppose we have Name and Surname properties. We can then define DisplayName property
get { return $"{this.Name} {this.Surname}"; }
I'm wondering if this is somehow possible in React, with state properties. It's legal to define a function as a value of state variable:
state = {
isSomethingTrue: function() {
return true;
},
};
However then we need to execute this function to get the value. Is there any way to do it in this way that calling this.state.isSomethingTrue will just return the calculated value?
You could implement that functionality like this:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
message: "Hello"
};
}
get isSomethingTrue() {
return this.state.message + " World";
}
render() {
return <div>{this.isSomethingTrue}</div>;
}
}
This is the demo:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
message: "Hello"
};
}
get isSomethingTrue() {
return this.state.message + " World";
}
render() {
return <div>{this.isSomethingTrue}</div>;
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></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