Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting code from using .bind(this) to arrow functions

I have recently been informed that it is not good to use bind(this) in the render function because it creates brand new functions every time. I am therefore moving towards using arrow functions as you see below in the two <button> elements.

The question I have is about the map function. It is also using .bind(this). Is there a way to convert this to an ES6/7 format?

return (
    <div>
        <button onClick={()=>this.changeDisplayType("images")}>Images</button>
        <button onClick={()=>this.changeDisplayType("audio")}>Audio</button>
        {
            resources.map(function(resource) {
                return (
                    <div key={resource.id}>
                        <div style={{fontWeight: "bold"}}>{resource.name}</div>
                        <div>({resource.info})</div>
                    </div>
                )
            }.bind(this))
        }


    </div>
)

I also just realized that I can remove the .bind(this) completely and my code still works. Therefore I am also wondering what difference it makes if its there or not.

like image 404
kojow7 Avatar asked Feb 22 '26 20:02

kojow7


1 Answers

Is there a way to convert this to an ES6/7 format?

Yes, you can write it like this by using arrow function:

resources.map(resource => {
    return (
        <div key={resource.id}>
            <div style={{fontWeight: "bold"}}>{resource.name}</div>
            <div>({resource.info})</div>
        </div>
    )
})

I can remove the .bind(this) completely and my code still works WHY?

Because you are not using this keyword in map body, means if you try to access any class property or method without binding the callback method, it will throw error.

Try this: remove binding and try to access the state value inside map body, it will throw error.

like image 73
Mayank Shukla Avatar answered Feb 25 '26 11:02

Mayank Shukla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!