Tell Babel to use h for the JSX function. That’s the /** @jsx h */ magic comment at the top.

Import both React and Preact. You’ll need both.

Make a Preact component. Or take one from somewhere else. It doesn’t matter. Whatever you want

Create a <Wrapper /> React component

That <Wrapper /> component is where the magic happens.

The render() method sets h to React.createElement and outputs an anchor div. Setting h ensures that this part of JSX compiles into React’s createElement calls. This makes the component integrate seamlessly with the rest of your project.

Then we hook into the component lifecycle with componentDidMount and componentDidUpdate. We call renderPreact in both of them to ensure our wrapper component always ends up rendering Preact.

In renderPreact, we then use Preact’s render() function to render the Preact component into our anchor div. This works the same way as Preact’s normal DOM rendering where you call render(<App />, document.getElementById('root')) to put your app into a root div.

The JSX compiles into Preact’s h() calls because we didn’t mess with the setting, and React refs give us a direct reference to the anchor DOM node.

The benchmark

You can now compare React and Preact side-by-side in my interactive DOM benchmark. I think it’s a fair comparison because Preact handles its own internals.

Numbers are kinda high though. Preact is supposed to be faster than React because it’s closer to the metal. I wonder if it’s running in dev mode

The post Seamlessly render a Preact component in a React project appeared first on A geek with a hat.