-2

I'm trying to convert the HTML template to react js. I have a js file where some functions are defined. Now when I tried to call that function in react js it shows me an error

'abc' is not defined no-undef

Below is the function and details how I use to call it:

class App extends React.Component {
  render() {
    return (
          <li>
             <a href="#" onClick={abc('purple')} title="purple" className="color">link</a>
          </li>
    );
  }
}


function.js

abc(color){
alert(color);
}

1 Answers1

0

You can use import and export instead.

In function.js

export abc(color){
  alert(color);
}

In your React component file

import { abc } from './function.js'
class App extends React.Component {
  render() {
    return (
          <li>
             <a href="#" onClick={()=>abc('purple')} title="purple" className="color">link</a>
          </li>
    );
  }
}
TmasYIN
  • 42
  • 2
  • what if I've multiple functions? do I need to import all? – Jashan Pabla Jul 25 '20 at 08:14
  • if you don't want to import the functions one by one, you can do like this: import * as myFunc from './function.js', and call the function by myFunc.abc() @JashanPabla – TmasYIN Jul 25 '20 at 08:33
  • my function.js is in public folder and I'm not able to import it in src folder app.js file.I've include it in public/index.html via script tag – Jashan Pabla Jul 25 '20 at 08:36
  • you can use ../ to travel to the upper directory @JashanPabla – TmasYIN Jul 25 '20 at 08:38
  • Relative imports outside of src/ are not supported. got this error – Jashan Pabla Jul 25 '20 at 08:38
  • You can choose either move those functions inside the src folder (preferred) or follow this solution [link](https://stackoverflow.com/a/44115058/10234091) to disable it. @JashanPabla – TmasYIN Jul 25 '20 at 08:43