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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With