DOM element styles
Manipulate DOM styles with ease.
Result box:
import {resetElementStyles, updateElementStyles} from '@kaiverse/k/utils'import {useRef} from 'react'
export default function DOMStylesDemo() { const resultBoxRef = useRef<HTMLDivElement>(null)
return ( <> <form id="color-form"> <label className="form-control w-full max-w-xs"> <span className="label label-text">Change background color π¨</span> <input className="input input-bordered w-full max-w-xs" name="inputColor" defaultValue="#000000" type="color" onChange={(e) => updateElementStyles(resultBoxRef.current, {'background-color': e.currentTarget.value}) } /> </label> </form>
<h3 className="mt-4">Result box:</h3> <div ref={resultBoxRef} className="h-32 bg-black rounded"></div> <button className="btn btn-neutral mt-4" form="color-form" type="reset" onClick={() => resetElementStyles(resultBoxRef.current, ['background-color'])} > Reset </button> </> )}updateElementStyles
Update styles of an element.
Type definition
function updateElementStyles( element: Element | HTMLElement | null, styles: CustomStyles, options?: UpdateStyleOptions,): void| Name | Type | Description |
|---|---|---|
CustomStyles | {[key: string]: string | number | undefined | null} | Styles to be updated. Key is CSS property name and should be a kebab-case string (eg: {'border-radius': '1rem'}). |
UpdateStyleOptions | {ignoreNilValue?: boolean; cache?: boolean | "once"} | updateElementStylesβs options |
Options
| Name | Type | Default | Description |
|---|---|---|---|
ignoreNilValue | boolean | false | If true, it will ignore updatiing the properties with undefined or null values. |
cache | boolean | "once" | false | Cache the original styles. Only cache value of provided properties that have been updated (depending on ignoreNilValue option).If set to "once", it wonβt override existing cached styles. |
resetElementStyles
Reset styles of an element.
Depending on provided properties, if the original styles have been cached, it will restore the original styles, otherwise, it will be removed from the current styles.
Type definition
function resetElementStyles(element: Element | HTMLElement | null, properties?: string[]): void