I have a Dashboard component, inside which I want to display multiple Charts (these charts can be line charts, bubble charts, you name it). For this example, I want to display a LineChart. You can see LineChart being passed in as the chartType value.
import React from 'react';
import Chart from './Chart';
import LineChart from '../LineChart';
const Dashboard = function () {
return (
<div>
<Chart chartType={LineChart} />
</div>
);
};
Chart acts like a generic wrapper, all it does is handle rendering, it shouldn't matter what chartType it is given as a parameter. If a LineChart obj is passed into it, it should render the LineChart component, if a ScatterChart obj then the ScatterChart component.
class Chart extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
};
this.ref = React.createRef();
this.myChartObj = new LineChart(props); // I DONT WANT THIS AS IT IS HARDCODING THE LINE CHART TYPE
// this.myChartObj = new props.chartType(props); // DOESNT WORK
}
componentDidMount() {
this.myChartObj.create(this.ref.current);
}
componentDidUpdate() {
this.myChartObj.update(this.ref.current);
}
render() {
return (
<div ref={this.ref} role="graphics-datachart" />
);
}
}
So I'm wondering how to instantiate a new LineChart object inside Chart's constructor by using the ChartType param. As you can see in the code, it's currently hardcoded with this.chartObj = new LineChart(props); Ideally, the solution would be something like this: this.chartObj = new props.chartType(props); because there's no hardcoding but it doesn't work and throws A constructor name should not start with a lowercase letter error.
Could anyone assist? Surely it should be OK to pass a class as a parameter and later use that parameter value to instantiate a new object of that class..? Any help would be greatly appreciated, thank you!
Edit: I'm aware that the error is being generated by my linter, but the question still stands as to how I instantiate an obj from a parameter. I'm getting a similar error in unit testing, which means that simply silencing my linter won't fit anything: TypeError: props.chartType is not a constructor
note: I'm using "chartType" in the stack question but its equivalent to d3Chart in screenshot