I try to use Preact for most of my projects but now I have a requirement to use a React component. I don't want this to require me to switch frameworks. Is there anything I can do to render the React component from my Preact code?
Render React component in Preact?
Preact provides a compatibility layer called preact-compat
.
You can use your module bundler to alias react
and react-dom
imports to use preact-compat
, and this should allow you to use React code in your Preact app unmodified.
Here is a Webpack example, taken from the preact-compat
docs:
{
// ...
resolve: {
alias: {
'react': 'preact-compat',
'react-dom': 'preact-compat',
// Not necessary unless you consume a module using `createClass`
'create-react-class': 'preact-compat/lib/create-react-class',
// Not necessary unless you consume a module requiring `react-dom-factories`
'react-dom-factories': 'preact-compat/lib/react-dom-factories'
}
}
// ...
}
Edit: As noted by @pmkro in the comments, from Preact 10.0 onwards, preact-compat
is being moved back into the core preact
package, and will be available via preact/compat
.
Thanks very much! –
Wenzel
Just as a note this is changing with
preact 10
. This is valid for 8.x
but for X its changed to preact/compat
and it ships with the rest of the package. –
Indented Thank you for the update @Indented - have been out of the Preact world for a little while so I wasn't aware. Will update my answer :) –
Surplice
© 2022 - 2024 — McMap. All rights reserved.