Reputation: 7092
I have a react component where I'm importing a function from another file like this:
import documentIcons from '/documentIcons';
Then I'm trying to use that function like this:
let file = this.state.selectedFile; //this returns fine
let fileExt = file.name.split('.').pop(); //this also works
let fileIcon = documentIcons(fileExt); //this throws the error
But I keep getting this error:
Uncaught TypeError: Object(...) is not a function
The documentIcons.js file looks like this:
const icons= {
"jlr": "/icn/typeA.png",
"trr": "/icn/typeB.png",
"bpx": "/icn/typeC.png",
};
export const documentIcons = (f) => {
this.icons.find(f)
}
I'm passing in a file extension(jlr, trr, or bpx) and I want the path to that icon returned.
Is there a way to do this in react/es6?
Thanks!
Upvotes: 0
Views: 102
Reputation: 191976
The documentIcons
is a named export, and should be imported as one:
import { documentIcons } from '/documentIcons'
The other option is to change the named export to a default export:
const documentIcons = (f) => {
this.icons.find(f) // this error is handled below
}
export default documentIcons
You should also remove the this
from the method, since icons
is a constant in the scope, and not a property on the same object. An object doesn't have the find
method, and you should use brackets notation to get the value, and then return it:
const documentIcons = (f) => icons[f]
Upvotes: 2
Reputation: 17608
There are a couple of missing parts here.
First of all export your function with default or import it as a named one:
import { documentIcons } from "/documentIcons";
Second one, you can't use .map
on an object. If you want to find the url with the object key, use it like this:
icons[f]
Third, your are not returning anything from your function. Use it like this:
export const documentIcons = (f) => icons.[f];
This is a shorthand for:
export const documentIcons = (f) => {
return icons.[f]
}
Upvotes: 1