Search code examples
reactjscoding-style

It's okay to define an object's property value relatively to its sibling?


For example:

state={ 
    viewIndex:0,
    travelerIndex: 100,
    viewValue: (this.stateviewIndex * this.state.travelerIndex)
  }

Here we can see that viewValue is defined relatively to viewIndex and travelerIndex. It seems a few recursive to me and I wonder if it's okay to do the thing like that.

Any hint would be great, thanks


Solution

  • I would create a local function that computes the total value from the state instead of adding a layer of complexity into the state. I've created an example below. You can use the return value to do whatever.

    class App extends React.Component {
      state = {
        tomsWallet: 50,
        hannahsPurse: 49,
      }
      getTotalBalance = () => {
        return (this.state.tomsWallet + this.state.hannahsPurse).toFixed(2);
      }
      render() {
        return (
          <div>Total Balance: £{this.getTotalBalance()}</div>
        )
      }
    }
    
    ReactDOM.render(<App/>, document.getElementById('root'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <div id="root"></div>