Ankit Kaushal
Ankit Kaushal

Reputation: 993

How to call a function of a react component in other js files inside the project

I have a React component file named FilterBox.jsx, it has a function with the following code:

addTimeFilter() {
   var clickedItem2 = sessionStorage.getItem("clicked_value");
   const fltr = TIME_FILTER_MAP['__time_range'];
   const vals = '2019-03-25T00:00:00 : 2019-03-26T00:00:00';
   const selectedValues = Object.assign({}, {"__time_range" : "2019-03-25T00:00:00 : 2019-03-26T00:00:00","BrandName" : clickedItem2});
   selectedValues[fltr] = vals;
   this.setState({ selectedValues, hasChanged: true });
   if (this.props.instantFiltering) {
      this.props.onChange(fltr, vals, false, true);
   }
}

I have another file which is a .js file. I want to call addTimeFilter() inside the .js file. Please help me how to do this.

I have tried to import it like this:

 import FilterBox from '../../FilterBox';

Then I tried doing this inside a function in the .js file to call the following function:

function select(){
     const filter = new FilterBox();
     filter.addTimeFilter();
}

But only the import FilterBox from '../../FilterBox' giving me errors

Upvotes: 1

Views: 101

Answers (2)

olajensola
olajensola

Reputation: 31

You have to export the addTimeFilter. Then when you import the function try this:


import { addTimeFilter } from '../../FilterBox';

I'm kinda new to react too, but something like this should work! :)

EDIT: try to export the class with "export default FilterBox" in the line in your file

Upvotes: 1

paragxviii
paragxviii

Reputation: 220

You need to write export keyword before the function name to let other js files know what to import.

export function addTimeFilter() {
/.../
}

Upvotes: 0

Related Questions