-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreact-accessing-the-dom-13-09-2022.jsx
39 lines (31 loc) · 1.21 KB
/
react-accessing-the-dom-13-09-2022.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// ⚠️ This snippet won't run, as I'm using a fictional UI library as an example! ⚠️
import React, { useEffect, useRef } from "react";
// This imported library doesn't exist. 🙅♀️ It's just here for the sake of the example!
import UILibraryElement from "ui-library-element";
const Component = ({ children }) => {
// Creating a ref with the useRef() hook. 🪝
const uiLibraryRef = useRef();
useEffect(() => {
// Add a useEffect callback here and using an UI library element to make it look cute. 💄
const node = uiLibraryRef.current;
UILibraryElement.initialize(node);
// Don't forget to return a cleanup function for when the component is unmounted. 🧹
// If not, we'll have event handlers polluting DOM nodes that aren't in the document anymore.
return () => node.uiLibraryRef.destroy();
// Remember to specify your effect's dependencies array! We know that our node will never change, so make it an empty array.
}, []);
// Adding the ref prop to the div. 👇
return (
<div ref={uiLibraryRef}>
<div>{children}</div>
</div>
);
};
const App = () => {
return (
<Component>
<div>UI Library Element</div>
</Component>
);
};
export default App;