DEV Community

skptricks
skptricks

Posted on

Why to use refs instead of IDs In React JS

Post Link : https://www.skptricks.com/2018/06/why-to-use-refs-instead-of-ids.html

Lets start with ID attribute in react js and here we have used ID attribute to access one of the element in react component. Actually in this IdComponent Component we are performing below operations :
When user focus on text field, then it will change the border color to Blue and background color to light black.
When user focus out of the text field, then it will reset the border color and border color to initial stage.

Why to use refs instead of IDs In React JS

The Reusability Problem
The problem you'll encounter , when you are using same component more than once. Here's a demo of re-usability issue with ID attribute, when you try to create that same component multiple times. Tap through the input fields to see what happens. Here we have created multiple objects with the same ID.

Solution is Ref
This component using Ref attribute to overcome above issue.

Top comments (1)

Collapse
 
arximughal profile image
Muhammad Arslan Aslam

You missed all of the code snippets while copying, I guess!!!! 😬