Strong Components
We consider a Strong Component a component that is primarily encapsulated and manages it's own state while exposing a programming interface for other components to interact with.
There are 2 main points to making a Strong Component:
- 1.Expose an imperative handle
- 2.Registering the component with the Reactium Component Registry
Considering we have a domain called: MyStrongComponent
index.js
import { useEventHandle } from '@atomic-reactor/reactium-sdk-core';
import React, { forwardRef, useImperativeHandle, useState } from 'react';
export default MyStrongComponent = forwardRef((props, ref) => {
const [state, setState] = useState({});
const someFunction = () => {};
const onClick = () => {
handle.dispatchEvent(new Event('click'));
};
const _handle = () => ({
someFunction,
setState,
state,
props,
});
const [handle, setHandle] = useEventHandle(_handle());
useImperativeHandle(ref, () => handle);
return (
<div>
<button onClick={() => onClick()}>Click It</button>
</div>
);
});
reactium-hooks.js
import Reactium from '@atomic-reactor/reactium-sdk-core';
import MyStrongComponent from './index';
Reactium.Component.register('MyStrongComponent', MyStrongComponent);
Now that we have the Strong Component set up, it can be used in any other component that uses the Reactium SDK regardless of where it lives or how it was created.
Some other React app
import React, { useEffect, useRef } from 'react';
import Reactium, { useHookComponent } from '@atomic-reactor/reactium-sdk-core';
export default MyOtherComponent = () => {
const mscRef = useRef();
const MyStrongComponent = useHookComponent('MyStrongComponent');
const onClick = e) => {
// log the MyStrongComponent current state
console.log('clicked', e.target.state);
// Update to the MyStrongComponent's state
e.target.setState({ updated: Date.now() });
};
// Listen for MyStrongComponent 'click' event
useEffect(() => {
mscRef.current.addEventListener('click', onClick);
return () => {
mscRef.current.removeEventListener('click', onClick);
}
});
return <MyStrongComponent ref={mscRef} />
};
Last modified 2yr ago