Calculating in React
React is a beautiful framework. If you are reading this, you probably have your own feelings about it. Building out a React application, you will probably end up delving into state and Redux. Instead of going into depth about those two, let’s assume you are aware of how state and Redux work. The store gives us access to a lot of information about state if a component has access to it. If you want to use a model’s data to create attributes for other objects, you will need access to that model’s properties. If you only want to calculations to render on the page, you can create variables within the render function and even pass them down to display presentational components.But, if you intend on using it as an object’s attribute that will be saved, here’s the trick:
What we see in this picture is an example of how you can safely do a calculation. Let’s pretend we have a form that takes in two numbers and we wish to store them individually but also want a value stored of them multiplied together. Adding an attribute to state right before submission allows us to ensure that the calculation will be as accurate as possible without worrying what might change from state throughout the component’s lifecycle. This function would be called when the user hits submit. If we create an action that takes in an object and dispatches it to our database, we can pass in our “const nuobj” with the desired calculations. We could even map other objects state to props and pass that in instead of this.state.num1 or 2! I hope this helps if you may be confused how to add calculations as an attribute in React.