score:1
bind
is just core javascript. It's how binding events works. It's not a React concept.
The following article explains it pretty well.
Bounded function in JavaScript is a function that is bounded to a given context. That means no matter how you call it, the context of the call will stay the same.
To create a bounded function out of the regular function, the bind method is used. bind method take context to which you want to bind your function as a first argument. The rest of arguments are arguments that will be always passed to such function. It returns a bounded function as a result.
http://reactkungfu.com/2015/07/why-and-how-to-bind-methods-in-your-react-component-classes/
Also, on a side note, you should do all of your event binding in your constructor, not in your render method. This will prevent multiple bind calls.
Here's another good bit of information on the subject. They say:
We recommend that you bind your event handlers in the constructor so they are only bound once for every instance
https://facebook.github.io/react/docs/reusable-components.html
score:2
one of the purpose of bind
in React ES6 classes is that you have to bind manually.
No Autobinding
Methods follow the same semantics as regular ES6 classes, meaning that >they don't automatically bind this to the instance. You'll have to >explicitly use .bind(this) or arrow functions =>:
We recommend that you bind your event handlers in the constructor so they >are only bound once for every instance:
constructor(props) {
super(props);
this.state = {count: props.initialCount};
this.tick = this.tick.bind(this); // manually binding in constructor
}
you can read more from the docs: https://facebook.github.io/react/docs/reusable-components.html
score:2
var cat = {
sound: 'Meow!',
speak: function () { console.log(this.sound); }
};
cat.speak(); // Output: "Meow!"
var dog = {
sound: 'Woof!'
};
dog.speak = cat.speak;
dog.speak(); // Output: "Woof!"
var speak = cat.speak;
speak(); // Output: "undefined"
speak = cat.speak.bind(dog);
speak(); // Output: "Woof!"
Explanation:
The value of "this" depends how the function is being called. When you provide this.alertSomething as your button's onClick handler, it changes how it will be called since you are providing a direct reference to that function, and it won't be called against your object instance (not sure if I'm phrasing that right).
The .bind function will return a new function where "this" is permanently set to the value passed to it.
ECMAScript 5 introduced Function.prototype.bind. Calling f.bind(someObject) creates a new function with the same body and scope as f, but where this occurs in the original function, in the new function it is permanently bound to the first argument of bind, regardless of how the function is being used.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
It's best to do this in your component's constructor so that .bind is happening just once for each of your handlers, rather than on every render.
Source: stackoverflow.com
Related Query
- Why is it necessary to use bind when working with ES6 and ReactJS?
- What is the purpose of having two running ports when we working with ReactJS and NodeJS?
- Why are we requiring React and ReactDOM as modules when working with Webpack? It takes long to produce output
- why when I use axios to post data to my mongodb cloud I got an object with _id and empty fields?
- When to use .toJS() with Immutable.js and Flux?
- Why and when do we need to bind functions and eventHandlers in React?
- When working with lists and keys in React, can Keys contain whitespace/spaces?
- How to connect state to props with mobx.js @observer when use ES6 class?
- Why does production build of React app (with Webpack and Babel) use wrong development env with HMR, which causes errors?
- Is the use of the <form> tag necessary in ReactJS that have HOC input tags that handle form-esque events and behaviour?
- Getting large cryptic errors and warnings when trying to use mongoose with webpack
- Why use ReactJS with ASP.NET CORE MVC?
- why and when use recompose branch?
- ReactJS - ref not working with connect and redux-form
- Why use Express with ReactJS
- How to use inheritance with React components and es6 classes
- Errors with Flow, ReactJS and ES6 classes
- How to properly use peerDependencies when publishing an NPM module (React component) with webpack? And use with npm link?
- Why and when to use componentDidMount in react js?
- Why do Material UI tabs stop working when I use a .map to populate the content dynamically instead of hard coding?
- Why the autofocus isn't working in ReactJS with antd?
- when to use this.props.children and why
- How to fix "TypeError: items.map is not a function" when working with React and APIs?
- Why is my ReactiveUserControl or React application not working with Selenium auto test and WinAppDriver (C# test solution)
- When is it necessary to use `rerender` with the React Testing Library?
- "jQuery is not defined" after require/import when use ES6 with Webpack 4
- ReactJS when Fetch POST, and use then function to setState
- Infinite loop when working with react and react-firebase-hooks
- How to use async/await with useEffect React hook, i tried a lot of examples and nothing is working
- How to assign a value to state and use setState in ReactJs with Typescript
More Query from same tag
- How to clear input fields after submit in react
- React Router not displaying first page in Cordova-built apk
- Invisible border applied to inputs on Apple IOS devices
- Webpack/Babel/React - "Uncaught SyntaxError: Unexpected token :"
- How to get custom headers in react javascript?
- Netlify renders 404 on page refresh (using React and react-router)
- After an check if something is not null I get a null or undefined type error. How?
- How to setup rollup for css modules in TypeScript
- I'm using React-Bootstrap. The e.preventDefault() is not working
- toggle background color of selected list item react.js
- Data Persistence Between Renders in Functional Component
- WebRTC getting Failed to execute 'addIceCandidate' on RTCPeerConnection error on console but can still display remote and local videos
- Redux initial state gets mutated even when using Object.assign
- Deploy React App using AWS Code Pipeline with build variables
- How to redirect to other page in react outside component in a function
- Can I pass dynamic values to ES6's Template Literals?
- Axios can't get object by ID react
- How can you return Redirect using React Router?
- Populate React prop object from async function
- how to fix TypeError: Cannot read property 'customers' of null
- Added key prop || Warning: Each child in a list should have a unique "key" prop
- React not turning HTML string from JSON into text
- useState hook has stale data
- Path is matching both routes, with params, and static
- Label must have associated control
- Getting error when try to find existing product from localStorage in JavaScript
- Make a Confirmation Modal using React & Redux
- React redux container with createselector that contains a promise
- How to get data from firebase cloud firestore in react
- ES6: fire React function