From da15481650b9f88b99934e9fd87f9177f5ea86a8 Mon Sep 17 00:00:00 2001 From: Marc Glasser Date: Mon, 10 Jan 2022 13:45:02 -1000 Subject: [PATCH 1/3] Add guidance on method binding for class components --- STYLE.md | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/STYLE.md b/STYLE.md index 7a9fe40deed97..8c3abad3c4d81 100644 --- a/STYLE.md +++ b/STYLE.md @@ -511,6 +511,48 @@ const propTypes = { } ``` +## Binding methods + +For class components, methods should be bound if be passed directly a prop or needing to be accessed via the component instance from outside of the component's execution context. Do not simply bind all methods in the constructor without reason. Learn and understand how `this` works [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this). + +```javascript +// Bad +class SomeComponent { + constructor(props) { + super(props); + + this.myMethod = this.myMethod.bind(); + } + + myMethod() {...} + + render() { + return ( + // No need to bind this since arrow function is used +