javascript - In react.js with chart.js, I can't access to my data in a componant - TagMerge
1In react.js with chart.js, I can't access to my data in a componantIn react.js with chart.js, I can't access to my data in a componant

In react.js with chart.js, I can't access to my data in a componant

Asked 1 years ago
0
1 answers

Accessing BarChart.data seems wrong as, BarChart is basically a functional React component.

What you want is probably this:

  1. You have a data array.
  2. You want to show that data in a BarChart
  3. You want to give a button to the user such that when user clicks that button, a new row is added into that data array.
  4. And when that data array changes, you want the BarChart to refresh and display the updated data array.

If this is the case, then I would recommend checking the Lifting State Up in the React docs. It is pretty much the same use case here. You have a single data source shared across 2 components.

Also, check the usage of React hooks for checking state usage: https://reactjs.org/docs/hooks-state.html

Here is a pseudocode you can try:

ParentComponent = () => {

    // 1. Create your data state here using React Hooks
    const [data, setData] = useState([someInitialData]);
    
    return (
        <div>
            // 2. BarChart now relies on the data in the state
            //    Whenever the data updates, the chart refreshes
            <BarChart data={data}/>
            // 3. Pass setData to the component and trigger it with the 
            //    button's onClick handler
            <ButtonChart updateData={setData}/>
        </div>
    );
}

Source: link

Recent Questions on javascript

    Programming Languages