7

React 18 introduced a new way to manually render a component, now instead of calling

import ReactDOM from 'react-dom';
ReactDOM.render(component, container)

one must call

import { createRoot } from 'react-dom/client';
createRoot(container).render(component);

Failure to do so results in a warning to the console and reverting back to React 17 API compatibility.

Is there an official or at least a semi-clean way for a component published to NPM to support both APIs?

There is React.version that I can check.

However createRoot is in a separate file, this means I am looking at a conditional import that will surely be source of problems with the various bundlers and transpilers.

Any better ideas?

Note: The component in question is https://www.npmjs.com/package/rlayers which includes a virtual component, the map style, with a render() property, that can be rendered off-screen to compute the map style. Any answer that allows me to call all the nested render() methods while providing a value for a context is also a valid one.

2
  • 1
    Does the npm package really include not only the component, but also the call to render/createRoot? If so, that's rather unusual. Most npm packages relating to react will just contain the components, and it's up to the app that uses those components to call render/createRoot Apr 2, 2022 at 18:23
  • 1
    Yes, it does, it is npmjs.com/package/rlayers for rendering maps - it includes a virtual component - the map style - that it is rendered off-screen - to compute the map style
    – mmomtchev
    Apr 2, 2022 at 18:27

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.