guest5541121
guest5541121

Reputation: 13

How to add a React method to an object outside of React

So, really straightforward issue here. I am using React Highcharts Official and for the options attribute on ReactHighcharts I want to import graphOptions from another file.

<ReactHighcharts highcharts={Highcharts} options={graphOptions} />

Now, this would be easy however on the file I'm trying to import, I have a method called this.addData().

export const graphOptions = {
    title: {
        text: 'title '
    },
    yAxis: {
        title: {
            text: 'Points'
        }
    },
    xAxis: {
         title: {
            text: 'Date'
        }
     },
    series: this.addData()
};

Ok, so I know I can have this file in my react render area but is there a way to import this there if I have a this statement on my series code as shown above?

Upvotes: 0

Views: 90

Answers (2)

ppotaczek
ppotaczek

Reputation: 39139

You can simply assign new property to graphOptions object in constructor, already having access to the appropriate method:

import options from "./options.js";

class App extends React.Component {
  constructor(props) {
    super(props);

    options.series = this.addData();
    this.state = {
      options: options
    };
  }

  addData() {
    return [
      {
        data: [1, 2, 3]
      }
    ];
  }

  render() {
    return (
      <HighchartsReact highcharts={Highcharts} options={this.state.options} />
    );
  }
}

Live demo: https://codesandbox.io/s/m7xvq7z468

Upvotes: 0

Umair Farooq
Umair Farooq

Reputation: 1833

One way could be to export function i.e getGraphOptions instead of object and then after importing, bind it with this of current react class.

export const function getGraphOptions() {
   return {
    // object
    series: this.addData()
}

and in the react file.

import { getGraphOptions } from './...'
this.getGraphOptions = getGraphOptions.bind(this);

Upvotes: 1

Related Questions