@logo-react/web-wrapper v1.0.0
Logo Elements Web Component Wrapper for React Applications
Use @logo-react/web-wrapper
to simplify usage of web components in React. This is a light wrapper to help manage events and props of the web component.
const MyComponent = logoWebWrapper('my-web-component');
The wrapper syncs props and events to the web component, including when they change and when the component is unmounted.
Installation
npm install --save @logo-react/web-wrapper
or
yarn add @logo-react/web-wrapper
Usage
Import logoWebWrapper
at the top:
import {logoWebWrapper} from '@logo-react/web-wrapper';
Create a new component that wraps your web component by calling the logoWebWrapper
function and pass the tag name of the web component.
const MyComponent = logoWebWrapper('my-web-component');
You can now use MyComponent
anywhere in your JSX as if it were a regular React component.
For example, you can set the someProp
property of the web component to an object:
const App = (props) => {
const someObj = {
prop1: 'bla'
}
return <MyComponent someProp={someObj}></MyComponent>;
}
Or register event handlers:
const App = (props) => {
const handleEvent = (e) => {}
return <MyComponent event={handleEvent}></MyComponent>;
}
All properties and events map exactly as they are defined on the web component.
Note: React events following the
onEvent
naming convention are also supported. For example, if you use theonClick
event on the React component, @logo-react/web-wrapper will register theclick
event with the web component.
Refs
Wrapped components support passing a ref
which will get a reference to the underlying web component.
Example with useRef
:
const App = (props) => {
let myRef = React.useRef();
const handleClick = () => {
console.log('web component reference', myRef.current)
}
return <MyComponent ref={myRef} onClick={handleClick}></MyComponent>;
}
Example with callback:
const App = (props) => {
const onRefChanged = (element) => {
console.log('web component reference', element)
}
return <MyComponent ref={onRefChanged}></MyComponent>;
}
Typescript
logoWebWrapper
supports optional props type to ensure type safety when using the component:
type PersonProps = {
personDetails: PersonDetails, // object
showName: boolean,
personCardInteraction: PersonCardInteraction // enum
}
const Person = logoWebWrapper<PersonProps>('logo-elements-tags-input');
By default, if no type is provided, any prop will be valid.
Example
Here is an example of using the logo-elements-date-picker
web component in React.
import React from 'react';
import '@logo-elements/date-picker';
import { logoWebWrapper } from '@logo-react/web-wrapper';
const DatePicker = logoWebWrapper('logo-elements-date-picker');
const App: React.FunctionComponent = () => {
const handleChange = (e) => {/**/}
const localizedStrings = {/**/}
return <DatePicker
label="When were you born?"
change={handleChange}
i18n={localizedStrings}>
</DatePicker>;
};
2 years ago