S
SolidJS4d ago
Ryan

Using `querySelector*()` in a set reference function

From time to time I find the need to do something like this:
const setCalloutElementRef = (element: HTMLDivElement) => {
const closeElements = element.querySelectorAll('[data-global-notification-close="true"]');
};

return (
<Callout
ref={setCalloutElementRef}
// ...
const setCalloutElementRef = (element: HTMLDivElement) => {
const closeElements = element.querySelectorAll('[data-global-notification-close="true"]');
};

return (
<Callout
ref={setCalloutElementRef}
// ...
The issue with this code is that element.querySelectorAll('[data-global-notification-close="true"]') does not return any data because the children are not available at that time. if I use queueMicrotask() like this:
const setCalloutElementRef = (element: HTMLDivElement) => {
queueMicrotask(() => {
const closeElements = element.querySelectorAll('[data-global-notification-close="true"]');
});
};

return (
<Callout
ref={setCalloutElementRef}
// ...
const setCalloutElementRef = (element: HTMLDivElement) => {
queueMicrotask(() => {
const closeElements = element.querySelectorAll('[data-global-notification-close="true"]');
});
};

return (
<Callout
ref={setCalloutElementRef}
// ...
While this seems to consistently work, using any type of async code like this always gives me a little fear that it will not work all the time. Is this is a safe way to make sure querySelector*() works or is there a better stable solution I should be done?
1 Reply
Madaxen86
Madaxen864d ago
Use it in onMount. Then all elements are rendered

Did you find this page helpful?