Collapsible elements with React Hooks

Today, we’re building this:

In React, we don’t have access to the underlying DOM element. To gain access to the element, we have to utilize the special ref property. Usually this property er associated with the useRef hook. However, it is also possible to pass a simple callback function to the ref property, like this:

1
2
3
4
5
6
7
8
9
const CallbackComponent = () => {
function callback(divNode) {
// Do something meaningful with the node here
}

return (
<div ref={callback}></div>
);
};