Storing React Class functions in separate files
Asked Answered
S

1

5

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.

Stradivari answered 13/11, 2017 at 21:14 Comment(1)
of course you can, you just need to make sure you keep the scope and context of variables and the this in a way that won't produce bugs. for example an external arrow function will have a different this context than the class. have you tried it an came across some issues?Striped
C
10

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>
Cetology answered 13/11, 2017 at 21:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.