node Dev
node Dev

Reputation: 69

How to update State of chart.js in React

I am passing data from parent to child component in react , from App.js to chart.js through props and the values are passsed and i can see them logged the the console in child component but i want to change the state of chart data property as the props values changed so that the graph also gets changed .

here is my code for child component/chart.js file

import { useState } from "react";
import { Line ,Bar} from "react-chartjs-2"

const Bargraph = ({totalIncome,Balance,Expenses}) => {

**console.log("data is ",totalIncome,Balance,Expenses)**

const [state,setState] = useState({

    labels:["Total Income","Expenses","Current Balance"],
    datasets:[{

        backgroundColor: 'rgba(75,192,192,1)',
        borderColor: 'rgba(0,0,0,1)',
        borderWidth: 2,
        data:[totalIncome,Balance,Expenses]

    }]
})



    return ( 
<section className="chart mb-4 mt-lg-5">

<div className="container-lg">
    <div className="text-center">

        <h2>  Income , Expenses and Current Balance  </h2>
        <p className="lead"> Bar graph showing Total icnome , Expenses and remaining balance </p>
    
    </div>

<div className="row justify-content-center align-items-center mt-3 g-4">

<div className="col-md-5">

<Line data={state}
    
    options={{
            title:{
              display:true,
              text:'Income , Expenses and Current Balance',
              fontSize:20
            },
            legend:{
              display:true,
              position:'right'
            }
          }}

 />




</div>


<div className="col-md-5">

<Bar data={state}
    
    options={{
            title:{
              display:true,
              text:'Income , Expenses and Current Balance',
              fontSize:20
            },
            legend:{
              display:true,
              position:'right'
            }
          }}

 />



</div>
</div>




</div>

</section>

     );
}
 
export default Bargraph;

Upvotes: 2

Views: 11417

Answers (3)

Taxel
Taxel

Reputation: 4207

The other answers about useEffect show how you can achieve this when using state. Your example, however, does not require state at all. Think about props as very similar to state: Changes trigger a rerender automatically so if you can calculate something directly from them, do it in the render function/functional component.


import { Line ,Bar} from "react-chartjs-2"

const Bargraph = ({totalIncome,Balance,Expenses}) => {

// simply calculate the chartData from the props
const chartData = {

    labels:["Total Income","Expenses","Current Balance"],
    datasets:[{

        backgroundColor: 'rgba(75,192,192,1)',
        borderColor: 'rgba(0,0,0,1)',
        borderWidth: 2,
        data:[totalIncome,Balance,Expenses]

    }]
}



    return ( 
<section className="chart mb-4 mt-lg-5">

<div className="container-lg">
    <div className="text-center">

        <h2>  Income , Expenses and Current Balance  </h2>
        <p className="lead"> Bar graph showing Total icnome , Expenses and remaining balance </p>
    
    </div>

<div className="row justify-content-center align-items-center mt-3 g-4">

<div className="col-md-5">

<Line data={chartData}
    
    options={{
            title:{
              display:true,
              text:'Income , Expenses and Current Balance',
              fontSize:20
            },
            legend:{
              display:true,
              position:'right'
            }
          }}

 />




</div>


<div className="col-md-5">

<Bar data={chartData}
    
    options={{
            title:{
              display:true,
              text:'Income , Expenses and Current Balance',
              fontSize:20
            },
            legend:{
              display:true,
              position:'right'
            }
          }}

 />



</div>
</div>




</div>

</section>

     );
}
 
export default Bargraph;

Upvotes: 5

Shafqat Jamil Khan
Shafqat Jamil Khan

Reputation: 1037

use useEffect to get updated values.

import { useState } from "react";
import { Line ,Bar} from "react-chartjs-2"

var Bargraph = ({totalIncome,Balance,Expenses}) => {

**console.log("data is ",totalIncome,Balance,Expenses)**

const [state,setState] = useState({

    labels:["Total Income","Expenses","Current Balance"],
    datasets:[{

        backgroundColor: 'rgba(75,192,192,1)',
        borderColor: 'rgba(0,0,0,1)',
        borderWidth: 2,
        data:[totalIncome,Balance,Expenses]

    }]
})

useEffect(() => {
    setState({
        labels:["Total Income","Expenses","Current Balance"],
        datasets:[{
            backgroundColor: 'rgba(75,192,192,1)',
            borderColor: 'rgba(0,0,0,1)',
            borderWidth: 2,
            data:[totalIncome,Balance,Expenses]
    
        }]
    })

}, [totalIncome,Balance,Expenses]);


    return ( 
<section className="chart mb-4 mt-lg-5">

<div className="container-lg">
    <div className="text-center">

        <h2>  Income , Expenses and Current Balance  </h2>
        <p className="lead"> Bar graph showing Total icnome , Expenses and remaining balance </p>
    
    </div>

<div className="row justify-content-center align-items-center mt-3 g-4">

<div className="col-md-5">

<Line data={state}
    
    options={{
            title:{
              display:true,
              text:'Income , Expenses and Current Balance',
              fontSize:20
            },
            legend:{
              display:true,
              position:'right'
            }
          }}

 />




</div>


<div className="col-md-5">

<Bar data={state}
    
    options={{
            title:{
              display:true,
              text:'Income , Expenses and Current Balance',
              fontSize:20
            },
            legend:{
              display:true,
              position:'right'
            }
          }}

 />



</div>
</div>




</div>

</section>

     );
}
 
export default Bargraph;

Upvotes: 3

Viet
Viet

Reputation: 12787

You can use useEffect to update your state when props change

  useEffect(() => {
    setState([
      {
        backgroundColor: "rgba(75,192,192,1)",
        borderColor: "rgba(0,0,0,1)",
        borderWidth: 2,
        data: [totalIncome, Balance, Expenses],
      },
    ]);
  }, [totalIncome, Balance, Expenses]);

Upvotes: 1

Related Questions