2

I have a react page that contains a pie chart. It returns this div as well as several other HTML components.

enter image description here

I also have 25 input fields that update 3 variables (incomeNum, expenseNum, and savingNum) as something is typed in any of the input fields (an onChange event in react).

enter image description here

The newData function looks like this. It successfully updates the 3 variables without a problem:

enter image description here

The pie chart is supposed to display the data from the incomeNum, expenseNum, and savingNum variables. My goal is to dynamically update the pie chart like I am to the incomeNum, expenseNum, and savingNum variables as the input fields are being filled out. My thinking was when I updated those three variables I could just update the dataSource (used by the pie chart) and it would update the pie chart, but the problem is the chart doesn't update itself unless you click on it. I want it to update without clicking on it.

Thanks for reading this.

btror
  • 113
  • 9
  • have u ever used, lifecycle methods? and also it's not very good to access DOM through vanilla methods, try using refs or state – Alopwer Nov 30 '20 at 21:18
  • I've never used lifecycle methods. I'm really new to React but I'll look into them. – btror Nov 30 '20 at 21:23
  • better read the essentials of react on the official website, they are pretty simple, from what i see you could create 3 or maybe 1 properties of state, and to update them if needed, when you update state, component rerenders and lifecycle methods are triggered, so the view changes, that's what you need – Alopwer Nov 30 '20 at 21:28
  • Well, it looks like I need to do some reading on lifecycles, states, and rendering. Thanks for the input. – btror Nov 30 '20 at 21:33

1 Answers1

1

You should not be updating HTML of a React component outside of React. This means you should either be using state hooks for procedural or setState for object oriented.

So, for example:

render() {
    return (<>
       <div id="income">
              ${this.state.incomeNum}
       </div>
       <input value={this.state.incomeNum} onChange={(evt) => this.setState({incomeNum: evt.target.value})} />
    </>)

Or, in procedural:

const [incomeNum, setIncomeNum] = useState(0);

return (
    <>
        <p>${incomeNum}</p>
        <input onChange={(evt) => setIncomeNum(evt.target.value)} value={incomeNum}>
    </>
);
cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
  • Ya, I'm going to restructure my code like that and see if a more obvious solution presents itself. Thanks for the feedback. – btror Dec 02 '20 at 02:33