@nrk/custom-element-to-react
Converts a custom element to a React component, with props and events.
Installation
npm install @nrk/custom-element-to-react
Usage
Given a custom element:
export default class MyElement extends HTMLElement { }
convert it to React component by passing in its class definition and a list of props and custom event names:
import React from 'react'
import ReactDOM from 'react-dom'
import customElementToReact from '@nrk/custom-element-to-react'
import element from './my-element.js'
const MyElement = customElementToReact(element, {
props: ['prop1', 'prop2'],
customEvents: ['event1', 'event2'],
suffix: '123'
})
ReactDOM.render(<MyElement />, document.getElementById('div'))
forwardRef
forwardRef
provides access to the underlying CustomElement (DOM) itself instead of the React component.
<MyElement
ref={(comp) => console.log('MyElement React Component:', comp)}
forwardRef={(node) => console.log('MyElement actual DOM Element:', node)}
/>
Server side
If you're going to use this module to render a component in NodeJS, you should
mock HTMLElement
globally in order to make MyElement extends HTMLElement
valid:
if (typeof window !== 'undefined' && !global.HTMLElement) {
global.HTMLElement = class {}
}
Local development
First clone @nrk/custom-element-to-react
and install its dependencies:
git clone git@github.com:nrkno/custom-element-to-react.git
cd custom-element-to-react
npm install
npm start
Building and committing
After having applied changes, remember to build before pushing the changes upstream.
git checkout -b feature/my-changes
npm run build
git commit -am "Add my changes"
git push origin feature/my-changes