#100DaysOfCode
Day 05: Manipulating the DOM with Refs
Cont.
Learned how we can manipulate the DOM with Refs in react. Using Refs we can create a reference to a particular node in DOM and then with the help of that Ref we can use browser APIs on that DOM node. By default, we cannot access the DOM nodes in event handlers.
Sometimes you need to Ref to each item in the list, so you cannot call useRef in a loop, condition, or a map() function because hooks are called at the top level of the component.
One way is to grab the parent node and then use the DOM manipulation methods to get the individual nodes but it could break if the DOM structure changes. So another way is by using a ref callback. Instead of referencing a particular node, now you are storing a list of nodes with their IDs in the Map data structure, all just by passing a function in the ref attribute.
Source article:
https://react.dev/learn/manipulating-the-dom-with-refs
By default, if you put a ref on your own component then the ref.current will print null. This is because react doesn’t let a component access other components' DOM nodes, even its child.
But it can be solved using the forwardRef API, which wraps the component that is to be referenced and it takes two arguments. First is the props, and second is the ref argument. Now this ref argument is passed to the node as a ref attribute.
It's so much fun using ref to manipulate the DOM, just don’t forget the rules. Maybe I was looking for something like this 😅
Best Practices:
- Avoid changing DOM nodes managed by React.
- If you do modify DOM nodes managed by React, modify parts that React has no reason to update.
Otherwise, React be like: how did you touch my property!!!
#reactjs #frontenddev #webdev #javascript #learnreact