Search code examples
reactjspreact

Render React component in Preact?


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?


Solution

  • 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.