Defining my function inside or outside the class - reactjs

So, this is just a best practices question.
If I have a create class like:
class Example extends Component {
method = () => {
return 'hello';
}
}
Versus:
methodFunction() {
return 'hello';
}
class Example extends Component {
method = () => {
return methodFunction;
}
}
What are the major differences? I get that if I need access to this, I won't have it in the methodFunction unless I pass it in. But, are there any other scope related gotchas to moving my functions outside of the class?
Also, I'm curious because, I'd like to move all the functions outside of the class. Seems like it would be easier to test functions this way.
Let me know what you think,
Cheers!

Related

How to export a function from a class, so to be able to import it into another class to use

To be clear, I am learning TypeScript and React for spfx developments. I have read and taken part in tutorials and other answers on various sources and Stack Overflow and haven't found them enough to help me.
Here is my function in the EvalReqNewForm class (getGrades()):
export default class EvalReqNewForm extends React.Component<IEvalReqNewProps, IEvalReqNewState> {
constructor(props){
super(props);
this.state = {
EvalType: null,
JobTitReportTo: null,
JobTitReportToNum: null,
PropGradeList: [],
SelectedGrade: undefined,
CompPos: null,
ContextNewJobCode: null
};
this._onJobTitReportToChange = this._onJobTitReportToChange.bind(this);
this._onJobTitReportToNumChange = this._onJobTitReportToNumChange.bind(this);
this._onPropGradeChange = this._onPropGradeChange.bind(this);
}
...
public _getGrades() {
pnp.sp.web.lists.getByTitle("Grades").items.get().then((items: any[]) =>{
let returnedGrades:IDropdownOption[]= items.map((item) =>{return {key:item.Title, text:item.Title};});
this.setState({PropGradeList : returnedGrades});
});
}
And I want to use the _getGrades() function from the other class to use in a ComponentDidMount() in order to the 'Grades' from the SP list.
Does it involve using props? Or can the function be simply exported and imported into the class where I want to use it?
Please understand I'm learning the basics here!
TL;DR
Create a function that only depends on it's parameters and export/import it.
Or can the function be simply exported and imported into the class where I want to use it?
What you can do is create a function that depends only on it's parameters.
So it would be something like
export function getGrades(something){
// do what ever you want with something
return somethingYouDid
}
And then you import it to other files and use it like
import { getGrades } from '...'
...
public _getGrades() {
const results = getGrades(someDataFromSomeWhere)
this.setState({PropGradeList : results});
}
I also see that you are using promises, so maybe you will need to use async/await in your case.
Edit:
As said in the comments
I can't seem to use export within a class
You should use it out side of the class, you will have to functions.
One out side of the class that have all the logic and other inside that class that only calls the outside function.
export function getGrades(something){
// do what ever you want with something
return somethingYouDid
}
class ... {
...
public _getGrades() {
const results = getGrades(someDataFromSomeWhere)
this.setState({PropGradeList : results});
}
}

mobx react action binding

For those who has written apps with mobx + react, I'm wondering if there's a better way to handle context issue (eg. this. returns undefined in mobx store) when using onClick event handler inside a react component w/ inject & observer.
I have been writing the handler like onClick={actionFromStore.bind(this.props.theStore)} to resolve that issue, but it seems like there should be more concise way to do this that I'm not aware of.
I'm not a mobx expert, any advice would be appreciated!
The actions here are async fetch requests
You can either use #action.bound decorator:
#action.bound
doSomething(){
// logic
}
or use labmda function which will preserve the context:
#action
doSomething = ()=> {
// logic
}
Since there is 2018, the best practice in React apps development is to use lambda functions as class properties instead of class methods.
The lambda function as class property resolves all issues that can happen with context. You don't have to bind methods to the specific context, if using it.
For example, you working with this in some class method:
export default class SomeClass {
myProp = "kappa"
myMethod() {
console.log(this.myProp)
}
}
In this case, if you will use it, e.g., like some event listener, this will be unexpectedly (actually, more than expected) change from SomeClass instance to other value. So, if you using class methods, you should modify you code like this:
export default class SomeClass {
constructor() {
this.myMethod = this.myMethod.bind(this)
}
myProp = "kappa"
myMethod() {
console.log(this.myProp)
}
}
In constructor you are binding your class method to context of SomeClass instance.
The best way to avoid this kind of unnecessary code (imagine, that you have 10+ of this type of methods - and you should bind each of them), is to simply use lambda functions:
export default class SomeClass {
myProp = "kappa"
myMethod = () => {
console.log(this.myProp)
}
}
That's it! Lambda functions have no context, so this will always point to the SomeClass instance. So, now you can decorate you class property as you wish:
export default class SomeClass {
myProp = "kappa"
#action
myMethod = () => {
console.log(this.myProp)
}
}
Note, that if you are using Babel, you have to use transform-class-properties plugin.
This question is more related to the core of JavaScript, so I advise you to read this MDN article for more information about this behavior.
Hope, this was helpful!
With Mobx 6, decorators are becoming more discouraged and cumbersome to use (requiring makeObservable(this) to be called carefully in the constructor, even in subclasses.)
I therefore now find it cleaner to use
doStuff = action(() => {
// stuff logic
})
rather than
#action.bound
doStuff() { ...
or
#action
doStuff = () => { ...
This pattern with no decorators also works in older Mobx versions.

React binding through constructor - possible to automate?

As per recommendations from others, I have been binding class methods in the constructor in React, for example:
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
I have components with many methods, and I am binding all of these methods to this. Argh, what a pain! To avoid repetitively maintaining this pattern, I built a function that would be called in the constructor in place of all the individual calls; it binds all the methods specific to that class, while a parent class would take care of its own methods moving up the classes. For example:
function bindClassMethodsToThis(classPrototype, obj) {
Object.getOwnPropertyNames(classPrototype).forEach(prop => {
if (obj[prop] instanceof Function && prop !== 'constructor') {
obj[prop] = obj[prop].bind(obj);
console.log(`${classPrototype.constructor.name} class binding ${prop} to object`);
}
});
}
class A {
constructor() {
bindClassMethodsToThis(A.prototype, this);
}
cat() {
console.log('cat method');
}
}
class B extends A {
constructor() {
super();
bindClassMethodsToThis(B.prototype, this);
}
dog() {
console.log('dog method');
}
}
let b = new B();
So, React and ES6 gurus, is this a reasonable approach, or I am doing something wrong here? Should I stick to the individual bindings to this?
Your strategy seems sound, though there are some edge cases that you may end up wanting to tackle. A library like react-autobind, which Alexander mentioned, takes care of some of these things for you, and if I were to use this strategy I would probably use a library like this one (or take a look into the source code to get an idea for what it does).
For completeness, some alternative approaches are:
Use class properties and arrow functions (along with any necessary Babel transforms) to create pre-bound methods:
class MyComponent extends React.Component {
handleChange = () => { /* ... */ }
}
Use a decorator, like the autobind decorator from core-decorators, along with any necessary Babel transforms (this was the strategy I used previously):
import { autobind } from 'core-decorators'
class MyComponent extends React.Component {
#autobind
handleChange() { /* ... */ }
}
Explore the use of Hooks (currently in alpha) to avoid the problem of binding all together (since state values and setters exists as local variables to be closed over). This is the strategy I've been preferring very recently, but please note it is still in the proposal state and may change. :)
Assuming you have Babel setup for it, you can also use arrow functions instead, avoiding the need to bind this:
class Foo extends React.Component {
handleClick = (event) => {
event.preventDefault()
}
render() {
return <div onClick={this.handleClick}>Click me</div>
}
}
One way to resolve this is to call bind in render:
onChange={this.handleChange.bind(this)}

Should class methods be created with arrow functions

When creating React components I sometimes on the web that methods are created with arrow function syntax, and sometimes without it. E.g.
class Component extends .... {
someFnk = (param) => { ... }
}
vs
class Component extends .... { someFnk(param) { ... } }
Which approach is better practice? Arrow function makes is safe to use this in function body, however I wonder when in React this could be an issue (when this could change)?
To rephrase the question: when arrow function syntax can safe me from creating a bug?
As long as you bind class methods in the constructor, the final, overall output is the same.
The following, once compiled operate in an identical manner.
class Foo extends React.Component {
constructor(props) {
super(props)
this.handleBla = this.handleBla.bind(this)
}
handleBla() {
}
}
class Foo extends React.Component {
handleBla = () => {
}
}
You say "why bind this when in React this won't change". That isn't actually true - all event handlers change the context of this. So make sure to either use the arrow function or bind for event handlers.
Transpiled
Once you transpile both through babel, you can see there is very little difference. The arrow function is simply mapped onto _this (remember this technique from pre-ES6 days?)
var Foo = function () {
function Foo() {
_classCallCheck(this, Foo);
this.handleBla = this.handleBla.bind(this);
}
_createClass(Foo, [{
key: "handleBla",
value: function handleBla() {
console.log(this);
}
}]);
return Foo;
}();
var Foo = function Foo() {
var _this = this;
_classCallCheck(this, Foo2);
this.handleBla = function () {
console.log(_this);
};
};
Summary:
It's basically the same, but you must use bind context (either via the arrow function or bind) if you intend to use them with events and reference the component. This extremely common as most event handlers refer to state, setState or props, and so you will need the correct this

bind(this) in ReactComponent.render() method

I have a quite big React.Component with more than ten bind(this) calls in its constructor.
I don't think .bind(this) in a constructor gives any help to understand my code especially when reading the code inside of render().
So, I came up with the following idea, however, do not find how to achieve this.
render() {
if (this.methodToBind.getThis() === this) {
this.methodToBind = this.methodToBind.bind(this);
}
}
Is there any possible way I can get this of a method (getThis() from the example above)?
If yes for the above, is it a good practice to do this?
rather then doing this,
constructor () {
super();
this.myFunc = this.myFunc.bind(this);
}
myFunc () {
// code here
}
You can do something like this.
constructor () {
super();
// leave the binding, it's just not what the cool kids do these days
}
myFunc = () => {
// see what I did here with = () => {}
// this will bind your `this` with it's parent
// lexical context, which is your class itself, cool right. Do this!
}
For a reference have a look at the MDN documentation for Arrow Functions
Where to Bind This?
When you create a function in a Class Based Component in React.js you must bind this in order to call it from the render method. Otherwise the function will not be in scope.
There are a few ways to do this.
Never bind this in the render method. Binding this in the render method will cause React to create a new function every time your Component is rerendered. This is why we most commonly bind in the constructor.
Bind in the constructor. By binding in the constructor, you can call your function in the render method by using this.FunctionName();
Example Bind This
Class MyClass extends Component {
constructor(props) {
super(props);
this.FunctionName = this.FunctionName.bind(this);
}
myFunc () {
// code here
}
render() {
this.FunctionName();
return(
<div>
...
</div>
);
}
}
User fat arrow functions instead of traditional function definitions. Fat arrow functions lexically bind the this value. So you do not have to add bind to the function in the constructor when you use the fat arrow function in the class.
Important - Fat arrow functions are not always available to use in a React class. Depending on how you setup React. You might have to install,
babel-plugin-transform-class-properties
Then add it to your .bablerc file like this,
{
"plugins": [
"transform-class-properties"
],
"presets": [
"react"
]
}
Example Fat Arrow
Class MyClass extends Component {
myFunc = () => {
// code here
}
render() {
this.FunctionName();
return(
<div>
...
</div>
);
}
}
Summary
Never bind a function in the render.
Always bind in the constructor when using a traditional function
this is automatically available on the function when using a fat arrow function.
Not sure.
I am usually doing something like this:
onClick={this.handleClick.bind(this)}
or:
onClick={e => this.handleClick(e)}

Resources