Search code examples
javascriptreactjschart.jsreact-chartjs-2

Updating a Pie Chart in React as Data is Entered


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.


Solution

  • 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}>
        </>
    );