0

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!

1
  • export default instead of export Commented Jul 13, 2018 at 19:41

2 Answers 2

2

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]
Sign up to request clarification or add additional context in comments.

1 Comment

Hi thanks, that took care of the 1st error. No I'm seeing this: Uncaught TypeError: Cannot read property 'icons' of undefined for this line : this.icons.find(f)
1

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]
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.