DEV Community

React — Access custom params in handlers the right way

Dinesh Pandiyan on June 06, 2019

TL;DR - You can access render time values in handlers without having to use anonymous arrow functions. Hint — leverage data attributes. React is g...
Collapse
 
sunnysingh profile image
Sunny Singh

I don't think that I would like to place data that I already have in the DOM and then retrieving it again from the DOM, but there could definitely be some use cases for this approach. Thanks for sharing!

Collapse
 
guico33 profile image
guico33

The example given isn't relevant. If the id is coming from the props object, one can simply read it from through the closure in which case passing the data as an id to the html element and reading it from the event is useless.

If performance is a concern, one can also create a new component, pass the the necessary data as a prop and define the callback in the child.
I guess the described method could be useful for optimisation when dealing with third-party components though.

Collapse
 
flexdinesh profile image
Dinesh Pandiyan

The example was to give an idea that values can be stored as data attributes. I'll update the example to access state values so it's obvious.

Collapse
 
wmoore98 profile image
William Moore

I like it. Seems like a simple, down and dirty way to avoid using anonymous functions when there isn't a better answer. There are plenty of places where this would have been handy. Thanks!

Collapse
 
kioviensis profile image
Max Tarsis

it's just awesome
thx a lot, man

Collapse
 
joeattardi profile image
Joe Attardi

This is a really cool idea! I am currently using anonymous arrow functions in my components/apps, maybe I'll refactor and use this approach.

Collapse
 
irreverentmike profile image
Mike Bifulco

So simple - but perfectly effective. Nice!