nickg
nickg

Reputation: 151

How do I access a module's method in React from another module?

Im trying to make a module of functions to be called in other modules. Just Like React does everywhere like axios.get() for example. I know about Flux and passing methods as props. But in this case all I want to do it is something like this:

var module1 = class module1 extends React.Component{
  render() {
      function module1Method(){
          console.log("Im from Module1");  
      }
      return (
         <div/>
    );
  }
}
export default module1;

///////////////////////////////////////  in another file

import module1 from "./module1";
var module2 = class module2 extends React.Component{
   render() {
       module1.module1Method();
       return (
          <div/>
       );
   }
}
export default module2;

Can someone please let me know what I'm missing? Module2 seems to see Module1 fine, but it just can't access any methods on it. Thanks so much for any help!

Upvotes: 0

Views: 3940

Answers (1)

Pop-A-Stash
Pop-A-Stash

Reputation: 6652

You don't need React.Component for that purpose. You just want a plain old JS module:

// ModuleOne.js
export function square(x) {
    return x * x;
}
export function hello() {
    return "Hello!";
}

// Another File
import {square, hello} from "ModuleOne";
var module2 = class module2 extends React.Component{
   render() {
       var someNumber = square(1,2);
       var someMessage = hello();
       return (
          <div/>
       );
   }
}
export default module2;

Upvotes: 1

Related Questions