Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing React Class functions in separate files

Is there a way to store the functions of a react class in a separate file then import those functions for use? The reason for wanting to do this would be purely to cut down on the size of my component and to group functions by category.

For instance:

import functionIWantToImport from '../functions/functionIWantToImport';
import anotherFunction from '../functions/anotherFunction';

Class Test extends React.Component {
   constructor(props){
       super(props);

       this.state = {};
   }

   //and then include the functions like below:
   functionIWantToImport;
   anotherFunction;
}

I know i can do this with helper functions that arent part of the component class. But I'd like to do it with my component functions to save space, and clean up my code.

like image 616
ncc Avatar asked Jan 30 '23 05:01

ncc


1 Answers

Use standard JS functions (not arrow functions), and bind the function to the instance in the constructor:

function externalMethod() { // simulates imported function
  return this.state.example;
}

class Test extends React.Component {
   constructor(props){
       super(props);

       this.state = { example: 'example' };
       
       this.externalMethod = externalMethod.bind(this);
   }

   render() {    
    return (
      <div>{ this.externalMethod() }</div>
    );
   }
}

ReactDOM.render(
  <Test />,
  test
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="test"></div>
like image 133
Ori Drori Avatar answered Feb 06 '23 14:02

Ori Drori