Answer the question
In order to leave comments, you need to log in
How to call a React component function from outside?
There is a Chart component (to create a chart chart.js ):
import React, { useState, useEffect, useRef } from 'react';
import ChartJs from 'chart.js';
const chartConfig = {
type: 'bar',
data: {
labels: [],
datasets: [{
label: '',
data: [],
backgroundColor: [],
borderColor: [],
borderWidth: 0,
barPercentage: 1.0
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
spanGaps: false,
legend: {
display: false
},
plugins: {
filler: {
propagate: false
}
},
tooltips: {
enabled: true
},
scales: {
xAxes: [{
gridLines: {
display: false,
offsetGridLines: true
}
}],
yAxes: [{
gridLines: {
color: 'rgba(242, 243, 244, 1.0)',
zeroLineWidth: 0
},
ticks: {
beginAtZero: true
}
}]
}
}
};
const Chart = (props) => {
const chartContainer = useRef(null);
const [chartInstance, setChartInstance] = useState(null);
const updateDataset = (datasetIndex, newLabels, newData) => {
chartInstance.data.labels = props.labels;
chartInstance.data.datasets[datasetIndex].data = props.data;
chartInstance.update();
};
useEffect(() => {
if (chartContainer && chartContainer.current) {
const newChartInstance = new ChartJs(chartContainer.current, chartConfig);
setChartInstance(newChartInstance);
}
}, [chartContainer]);
return (
<React.Fragment>
<canvas ref={chartContainer} />
</React.Fragment>
);
};
export default Chart;
import Chart from '../../components/Chart';
<Chart />
<Chart />
Answer the question
In order to leave comments, you need to log in
1) How does updateDataset work? What does it change if it doesn't change the state? It calls the chartInstance properties, but I don't see where you use this object?
2) The React logic is such that all communication from the parent to the children goes exclusively through props, so if you want to change something in the child element, you must change the state of the parent so that the necessary props are passed to the child element, which are processed would be in a child element. For example, in the parent draw an element like this
<Chart updateData={ [datasetIndex, newLabels, newData] }/>
if (props.updateData) updateDataset(...props.updateData)
let updateDataHandler = {}
return <Chart updateDataHandler={ h => { updateDataHandler = h } }/>
props.updateDataHandler(updateDataset)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question