Skip to content

JochenDiekenbrock/use-custom-element

This branch is 1 commit ahead of the-road-to-learn-react/use-custom-element:master.

Folders and files

NameName
Last commit message
Last commit date

Latest commit

e177a53 · May 11, 2022

History

9 Commits
Jun 12, 2020
Jun 26, 2019
Jun 4, 2019
Jun 26, 2019
Jun 4, 2019
Jun 4, 2019
Jun 4, 2019
Jun 4, 2019
Jun 4, 2019
Jun 8, 2019
Jun 26, 2019
May 11, 2022
Jun 26, 2019

Repository files navigation

useCustomElement React Hook

Build Status Slack Greenkeeper badge NPM

Custom hook to bridge Custom Elements (Web Components) to React.

Installation

npm install use-custom-element

Usage

In this scenario, we are using a specific Dropdown Web Component as a React Dropdown Component. By using the custom React hook, we can provide all props in the right format to the custom element and register all event listeners (e.g. onChange from props) behind the scenes.

import React from 'react';

// Web Component Use Case
// install via npm install road-dropdown
import 'road-dropdown';

import useCustomElement from 'use-custom-element';

const Dropdown = props => {
  const [customElementProps, ref] = useCustomElement(props);

  return <road-dropdown {...customElementProps} ref={ref} />;
};

Afterward, the Dropdown component can be used:

const props = {
  label: 'Label',
  option: 'option1',
  options: {
    option1: { label: 'Option 1' },
    option2: { label: 'Option 2' },
  },
  onChange: (value) => console.log(value),
};

return <Dropdown {...props} />;

Custom Mapping

You can also define a custom mapping:

import React from 'react';

// Web Component Use Case
// install via npm install road-dropdown
import 'road-dropdown';

import useCustomElement from 'use-custom-element';

const Dropdown = props => {
  const [customElementProps, ref] = useCustomElement(props, {
    option: 'selected',
    onChange: 'click',
  });

  console.log(customElementProps);

  // label: "Label"
  // options: "{"option1":{"label":"Option 1"},"option2":{"label":"Option 2"}}"
  // selected: "option1"

  // and "onChange" mapped to "click" event for the event listener

  return <my-dropdown {...customElementProps} ref={ref} />;
};

Contribute

  • git clone [email protected]:the-road-to-learn-react/use-custom-element.git
  • cd use-custom-element
  • npm install
  • npm run test

More

About

Custom hook to bridge Custom Elements (Web Components) to React.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 100.0%