I am trying to use props
value in dataPointSelection
in apexchart
under state but I am getting error that this.props
is undefined and also value not showing on console log. Here is my code that I did:
constructor(props) {
super(props);
const { t, too, fromm } = this.props;
console.log("Upper" + this.props.fromm);
this.state = {
...props,
options: {
chart: {
id: "Speeding",
events: {
dataPointSelection: function(event, chartContext, opts) {
switch (opts.w.config.xaxis.categories[opts.dataPointIndex]) {
case "0-10":
window.open(
window.location.origin +
`/overspeeding/10/0/${
this.props.too ? `${this.props.too}` : `${cc}`
}/${
this.props.fromm ? `${this.props.fromm}` : "2016-01-04"
}` // in this line i am getting error
);
How to resolve this error and user props value in event?
The problem is that inside of the function
, you don't have access to the same this
than in the constructor. Instead you have access to the passed props
object, that contains the props.
You should be fine by just replacing this.props
with props
there:
constructor(props) {
super(props);
const { t, too, fromm } = props;
console.log("Upper" + props.fromm);
this.state = {
...props,
options: {
chart: {
id: "Speeding",
events: {
dataPointSelection: function(event, chartContext, opts) {
switch (opts.w.config.xaxis.categories[opts.dataPointIndex]) {
case "0-10":
window.open(
window.location.origin +
`/overspeeding/10/0/${
props.too ? `${props.too}` : `${cc}`
}/${
props.fromm ? `${props.fromm}` : "2016-01-04"
}` // in this line i am getting error
);
Another way would be to bind the upper this
to the new function using .bind(this)
, or just using an arrow function that doesn't have its own `this:
constructor(props) {
super(props);
const { t, too, fromm } = this.props;
console.log("Upper" + this.props.fromm);
this.state = {
...props,
options: {
chart: {
id: "Speeding",
events: {
dataPointSelection: (event, chartContext, opts) => { // Arrow funciton
switch (opts.w.config.xaxis.categories[opts.dataPointIndex]) {
case "0-10":
window.open(
window.location.origin +
`/overspeeding/10/0/${
this.props.too ? `${this.props.too}` : `${cc}`
}/${
this.props.fromm ? `${this.props.fromm}` : "2016-01-04"
}` // in this line i am getting error
);
Using function.bind
:
constructor(props) {
super(props);
const { t, too, fromm } = this.props;
console.log("Upper" + this.props.fromm);
this.state = {
...props,
options: {
chart: {
id: "Speeding",
events: {
dataPointSelection: function(event, chartContext, opts) {
switch (opts.w.config.xaxis.categories[opts.dataPointIndex]) {
case "0-10":
window.open(
window.location.origin +
`/overspeeding/10/0/${
this.props.too ? `${this.props.too}` : `${cc}`
}/${
this.props.fromm ? `${this.props.fromm}` : "2016-01-04"
}` // in this line i am getting error
);
// ...
}
}.bind(this)// Binding the upper this to function scope.
// ...