Dynamic Updates

Update timepicker options dynamically without destroying the instance

💡

Update Method

Use the update() method to change options on an existing timepicker instance without recreating it.

Interactive Demo

Change options dynamically and see the timepicker update:

import { useState, useEffect, useRef, useMemo } from 'react';
import { TimepickerUI } from 'timepicker-ui';
function DynamicTimepicker() {
const inputRef = useRef<HTMLInputElement>(null);
const pickerRef = useRef<TimepickerUI | null>(null);
const [clockType, setClockType] = useState<'12h' | '24h'>('12h');
const [theme, setTheme] = useState<'basic' | 'dark'>('basic');
const options = useMemo(() => ({
clockType,
theme,
}), [clockType, theme]);
useEffect(() => {
if (!inputRef.current) return;
if (pickerRef.current) {
// Update existing picker
pickerRef.current.update({ options });
} else {
// Create initial picker
pickerRef.current = new TimepickerUI(inputRef.current, options);
pickerRef.current.create();
}
return () => {
pickerRef.current?.destroy();
};
}, [options]);
return (
<>
<button onClick={() => setClockType(
clockType === '12h' ? '24h' : '12h'
)}>
Toggle Format
</button>
<input ref={inputRef} type="text" />
</>
);
}

Update Method

The update method allows you to change options without destroying the picker:

import { TimepickerUI } from 'timepicker-ui';
const input = document.querySelector('#timepicker');
const picker = new TimepickerUI(input, {
clockType: '12h',
theme: 'basic'
});
picker.create();
// Later, update options
picker.update({
options: {
clockType: '24h',
theme: 'dark'
}
});
// Or with create option to reinitialize
picker.update({
options: {
clockType: '12h'
},
create: true
});

Update with Callbacks

Update options including event callbacks:

import { TimepickerUI } from 'timepicker-ui';
const input = document.querySelector('#timepicker');
const picker = new TimepickerUI(input);
picker.create();
// Update with new callbacks
picker.update({
options: {
onConfirm: (data) => {
console.log('New time selected:', data);
},
onCancel: () => {
console.log('Selection cancelled');
}
}
});

Conditional Updates

Update picker based on user preferences or app state:

import { TimepickerUI } from 'timepicker-ui';
const input = document.querySelector('#timepicker');
const picker = new TimepickerUI(input);
picker.create();
// Update based on user preference
function updatePickerTheme(isDarkMode: boolean) {
picker.update({
options: {
theme: isDarkMode ? 'dark' : 'basic'
}
});
}
// Update based on device
function updateForMobile(isMobile: boolean) {
picker.update({
options: {
mobile: isMobile,
animation: !isMobile // Disable animation on mobile
}
});
}
// Listen to system theme changes
window.matchMedia('(prefers-color-scheme: dark)')
.addEventListener('change', (e) => {
updatePickerTheme(e.matches);
});