Search code examples
reactjsdomparserreact-domselectors-api

ReactDOM render -> DOMParser -> querySelectorAll -> returning null


const temp = document.createElement('div');
ReactDOM.render(component, temp);
const parsed = new DOMParser().parseFromString(
  temp.innerHTML,
  'text/html'
);
parsed.querySelectorAll(selector); // <- returns null rather than NodeList

^ There is an obscure use-case in my app, centered around needing to render the full tree of a component and query it for certain css classes for diffing against a subset of rules in external stylesheets.

Don't judge! :-)

I think I'm doing the above in a manner that I could reasonably expect to give me a proper result but clearly I'm missing something.


Solution

  • const temp = document.createElement('div');
    ReactDOM.render(component, temp, () => {
      const parsed = new DOMParser().parseFromString(
        temp.innerHTML,
        'text/html'
      );
      const selected = parsed.querySelectorAll(selector);
    });
    

    As with many such bugs, this one came down to a race condition. The render was taking long enough that the first argument for parseFromString was not available synchronously. Using the optional callback for ReactDOM.render fixed this.