Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define calculated state variable in React?

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?

like image 419
Arkadiusz Kałkus Avatar asked Mar 02 '26 14:03

Arkadiusz Kałkus


1 Answers

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>
like image 94
You Nguyen Avatar answered Mar 05 '26 02:03

You Nguyen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!