Skip to content

Wrapper for Web Components so that React will play nice

License

Notifications You must be signed in to change notification settings

dynata/react-web-component

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

React Web Component

Wrapper for Web Components so that React will play nice

Description

The wrapper makes for a smooth transition between React and Web Components by allowing to pass objects as attributes, and listen to custom events. Simple attributes (strings, numbers, booleans) are passed in on creation, while complex attributes (objects, arrays) are passed in when the element is mounted.

The custom events are generated by convention. if you add: onEvent={onEvent}, "on" is removed, and the remainder is lower-cased. In this case it will look for a event event:

element.addEventListener('event', callback);

Events with hyphens are now supported:

<Component 
   onCustomEvent={() => { console.log('custom event'); }}
/>

Same as:

element.addEventListener('custom-event', callback);

Example

export default function Chart ({ title, total, data }) {
	
	function onCustomEvent (e) {
		console.log('onCustomEvent', e);
	}
	
	return (
		<WebComponent
			component="chart-pie"
			header={title}
			total={total}
			data={data}
			onCustomEvent={onCustomEvent}
		>
			<div>child</div>
		</WebComponent>
	);
}

State/Props

A WebComponent can be updated like any other React Component. Under the hood, shouldComponentUpdate always returns false (The JSX is never re-rendered), and instead, the web component's properties are passed in.

If deep is passed as a prop, shouldComponentUpdate will do a deep comparison. It defaulst to shallow.

Value

WebComponent has a value getter, which can come in handy if you need to uses refs.

Properties/Attributes

In spite of their similarity, properties and attributes ae not the same. It is important that your web component uses best practices and syncs them, so that element.foo = true works the same way as element.setAttribute('foo', true);.

Obviously, you can't set an object via attributes (it coerces into a string). In these cases, they are always passed in as properties.

onUnmount

If desired, pass in an onUnmount callback which will be fired on componentWillUnmount, passing the custom element.

License

As always, free as in beer.

About

Wrapper for Web Components so that React will play nice

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 97.3%
  • HTML 2.7%