@vovikilelik/use-html
v1.2.1
Published
Hook and utils for DOM manipulations
Downloads
12
Maintainers
Readme
It is cover for html-js utils.
Abstract
The use-html
package includes a react hook that allows you to access an HTML element and a set of html-js utilities for manipulating the DOM.
Links
- html-js utils package.
- Wiki documentation.
- Git repository.
Features
- Manipulation with DOM.
- Call to clear function before new rendering.
For more features see html-js library.
Example
You can use the useHtml
hook to access a DOM element. The builder
function implements element management. Inside you can use the html-js utility.
export const Component: React.FC = () => {
const ref = useHtml(element => { /* DOM manipulations */ });
return <div ref={ref} />;
};
useHtml
accepts a method that can return a cleanup function.
const builder: HtmlBuilder<HTMLDivElement> = element => {
const unsubscriber = subscribe(element, {
click: () => console.log('Click')
});
/* DOM manipulations */
return unsubscriber;
};
export const Component: React.FC = () => {
const ref = useHtml(builder);
return <div ref={ref} />;
};
Uses
This package contains several hooks that will help you access DOM elements:
useHtml()
- base hook.useLayoutHtml()
- likeuseLayoutEffect()
.
Its usage is similar to useRef()
.
const builder = () => { ... };
export const Component: React.FC = () => {
const ref = useHtml(builder);
return <div ref={ref} />;
};
The builder
function is passed as an argument, which implements DOM manipulation and returns a cleanup function.
const builder: HtmlBuilder<HTMLDivElement> = element => {
/* DOM manipulations */
return () => { /* clean function */ };
};
You can pass multiple builders as an array.
const ref = useHtml([builder1, builder2, builder3]);
Transferred builder need to be memoized or store in variable.
const builder = () => { ... };
/* or const builder = [builder1, builder2, builder3]; */
export const Component: React.FC = () => {
const ref = useHtml(builder);
...
};
You can also pass dependencies as the second argument, if necessary.
const ref = useHtml(builder, [deps1, deps2]);
Lastly, use the html-js utility in builders.