Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-native-timer-picker

Package Overview
Dependencies
Maintainers
0
Versions
36
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-native-timer-picker

A simple, flexible, performant duration picker for React Native apps 🔥 Great for timers, alarms and duration inputs ⏰🕰️⏳ Includes iOS-style haptic and audio feedback 🍏

  • 2.0.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
0
Created
Source

React Native Timer Picker ⏰🕰️⏳

license platforms Version npm

A simple, flexible, performant duration picker component for React Native apps 🔥

Great for timers, alarms and duration inputs.

Works with Expo and bare React Native apps ✅

Includes iOS-style haptic and audio feedback 🍏


Demos 📱

Try it out for yourself on Expo Snack! Make sure to run it on a mobile to see it working properly.


Peer Dependencies 👶

This component will work in your React Native Project without any peer dependencies.

Linear Gradient

If you want the numbers to fade in/out at the top and bottom of the picker, you will need to install either:

To enable the linear gradient, you need to supply the component as a prop to either TimerPickerModal or TimerPicker.

Haptic Feedback

Enable haptic feedback with the expo-haptics module:

import * as Haptics from "expo-haptics";

To enable haptic feedback, you need to supply the imported Haptics namespace as a prop to either TimerPickerModal or TimerPicker.

Generic feedback support is possible with the pickerFeeback prop.

Audio Feedback (Click Sound)

Enable audio feedback with the expo-av module:

import { Audio } from "expo-av";

To enable audio feedback, you need to supply the imported Audio class as a prop to either TimerPickerModal or TimerPicker.

Please note that the default click sound uses a hosted mp3 file. To make the click sound work offline, you need to supply your own sound asset through the clickSoundAsset prop. You can download the default click sound here.

Generic feedback support is possible with the pickerFeeback prop.


Installation 🚀

Supports React Native >= 0.59.0 and React >= 16.8.0.

Just run:

npm install react-native-timer-picker

or

yarn add react-native-timer-picker

Examples 😎

Timer Picker Modal (Dark Mode) 🌚

import { TimerPickerModal } from "react-native-timer-picker";
import { LinearGradient } from "expo-linear-gradient"; // or `import LinearGradient from "react-native-linear-gradient"`
import { Audio } from "expo-av"; // for audio feedback (click sound as you scroll)
import * as Haptics from "expo-haptics"; // for haptic feedback

....
const [showPicker, setShowPicker] = useState(false);
const [alarmString, setAlarmString] = useState<
        string | null
    >(null);

const formatTime = ({
    hours,
    minutes,
    seconds,
}: {
    hours?: number;
    minutes?: number;
    seconds?: number;
}) => {
    const timeParts = [];

    if (hours !== undefined) {
        timeParts.push(hours.toString().padStart(2, "0"));
    }
    if (minutes !== undefined) {
        timeParts.push(minutes.toString().padStart(2, "0"));
    }
    if (seconds !== undefined) {
        timeParts.push(seconds.toString().padStart(2, "0"));
    }

    return timeParts.join(":");
};

return (
    <View style={{backgroundColor: "#514242", alignItems: "center", justifyContent: "center"}}>
        <Text style={{fontSize: 18, color: "#F1F1F1"}}>
            {alarmStringExample !== null
                ? "Alarm set for"
                : "No alarm set"}
        </Text>
        <TouchableOpacity
            activeOpacity={0.7}
            onPress={() => setShowPicker(true)}>
            <View style={{alignItems: "center"}}>
                {alarmString !== null ? (
                    <Text style={{color: "#F1F1F1", fontSize: 48}}>
                        {alarmString}
                    </Text>
                ) : null}
                <TouchableOpacity
                    activeOpacity={0.7}
                    onPress={() => setShowPicker(true)}>
                    <View style={{marginTop: 30}}>
                        <Text
                            style={{
                                paddingVertical: 10,
                                paddingHorizontal: 18,
                                borderWidth: 1,
                                borderRadius: 10,
                                fontSize: 16,
                                overflow: "hidden",
                                borderColor: "#C2C2C2",
                                color: "#C2C2C2"
                                }}>
                            Set Alarm 🔔
                        </Text>
                    </View>
                </TouchableOpacity>
            </View>
        </TouchableOpacity>
        <TimerPickerModal
            visible={showPicker}
            setIsVisible={setShowPicker}
            onConfirm={(pickedDuration) => {
                setAlarmString(formatTime(pickedDuration));
                setShowPicker(false);
            }}
            modalTitle="Set Alarm"
            onCancel={() => setShowPicker(false)}
            closeOnOverlayPress
            Audio={Audio}
            LinearGradient={LinearGradient}
            Haptics={Haptics}
            styles={{
                theme: "dark",
            }}
            modalProps={{
                overlayOpacity: 0.2,
            }}
        />
    </View>
)

Timer Picker Modal (Light Mode) 🌞

import { TimerPickerModal } from "react-native-timer-picker";
import { LinearGradient } from "expo-linear-gradient"; // or `import LinearGradient from "react-native-linear-gradient"`
import { Audio } from "expo-av"; // for audio feedback (click sound as you scroll)
import * as Haptics from "expo-haptics"; // for haptic feedback

....
const [showPicker, setShowPicker] = useState(false);
const [alarmString, setAlarmString] = useState<
        string | null
    >(null);

const formatTime = ({
    hours,
    minutes,
    seconds,
}: {
    hours?: number;
    minutes?: number;
    seconds?: number;
}) => {
    const timeParts = [];

    if (hours !== undefined) {
        timeParts.push(hours.toString().padStart(2, "0"));
    }
    if (minutes !== undefined) {
        timeParts.push(minutes.toString().padStart(2, "0"));
    }
    if (seconds !== undefined) {
        timeParts.push(seconds.toString().padStart(2, "0"));
    }

    return timeParts.join(":");
};

return (
    <View style={{backgroundColor: "#F1F1F1", alignItems: "center", justifyContent: "center"}}>
        <Text style={{fontSize: 18, color: "#202020"}}>
            {alarmStringExample !== null
                ? "Alarm set for"
                : "No alarm set"}
        </Text>
        <TouchableOpacity
            activeOpacity={0.7}
            onPress={() => setShowPicker(true)}>
            <View style={{alignItems: "center"}}>
                {alarmString !== null ? (
                    <Text style={{color: "#202020", fontSize: 48}}>
                        {alarmString}
                    </Text>
                ) : null}
                <TouchableOpacity
                    activeOpacity={0.7}
                    onPress={() => setShowPicker(true)}>
                    <View style={{marginTop: 30}}>
                        <Text
                            style={{paddingVertical: 10,
                            paddingHorizontal: 18,
                            borderWidth: 1,
                            borderRadius: 10,
                            fontSize: 16,
                            overflow: "hidden",
                            borderColor: "#8C8C8C",
                            color: "#8C8C8C"
                            }}>
                            Set Alarm 🔔
                        </Text>
                    </View>
                </TouchableOpacity>
            </View>
        </TouchableOpacity>
        <TimerPickerModal
            visible={showPicker}
            setIsVisible={setShowPicker}
            onConfirm={(pickedDuration) => {
                setAlarmString(formatTime(pickedDuration));
                setShowPicker(false);
            }}
            modalTitle="Set Alarm"
            onCancel={() => setShowPicker(false)}
            closeOnOverlayPress
            use12HourPicker
            Audio={Audio}
            // supply your own custom click sound asset
            clickSoundAsset={require("./assets/custom_click.mp3")}
            LinearGradient={LinearGradient}
            Haptics={Haptics}
            styles={{
                theme: "light",
            }}
        />
    </View>
)

Timer Picker with Customisation (Dark Mode) 🌒

import { TimerPicker } from "react-native-timer-picker";
import { LinearGradient } from "expo-linear-gradient"; // or `import LinearGradient from "react-native-linear-gradient"`
import { Audio } from "expo-av"; // for audio feedback (click sound as you scroll)
import * as Haptics from "expo-haptics"; // for haptic feedback

....
const [showPicker, setShowPicker] = useState(false);
const [alarmString, setAlarmString] = useState<
        string | null
    >(null);

return (
    <View style={{backgroundColor: "#202020", alignItems: "center", justifyContent: "center"}}>
        <TimerPicker
            padWithNItems={2}
            hourLabel=":"
            minuteLabel=":"
            secondLabel=""
            Audio={Audio}
            LinearGradient={LinearGradient}
            Haptics={Haptics}
            styles={{
                theme: "dark",
                backgroundColor: "#202020",
                pickerItem: {
                    fontSize: 34,
                },
                pickerLabel: {
                    fontSize: 32,
                    marginTop: 0,
                },
                pickerContainer: {
                    marginRight: 6,
                },
                pickerItemContainer: {
                    width: 100
                },
                pickerLabelContainer: {
                    right: -20,
                    top: 0,
                    bottom: 6,
                    width: 40,
                    alignItems: "center",
                },
            }}
        />
    </View>
)

Timer Picker with Customisation (Light Mode) 🌔

import { TimerPicker } from "react-native-timer-picker";
import { LinearGradient } from "expo-linear-gradient"; // or `import LinearGradient from "react-native-linear-gradient"`
import { Audio } from "expo-av"; // for audio feedback (click sound as you scroll)
import * as Haptics from "expo-haptics"; // for haptic feedback

....
const [showPicker, setShowPicker] = useState(false);
const [alarmString, setAlarmString] = useState<
        string | null
    >(null);

return (
    <View style={{backgroundColor: "#F1F1F1", alignItems: "center", justifyContent: "center"}}>
        <TimerPicker
            padWithNItems={3}
            hideHours
            minuteLabel="min"
            secondLabel="sec"
            Audio={Audio}
            LinearGradient={LinearGradient}
            Haptics={Haptics}
            styles={{
                theme: "light",
                pickerItem: {
                    fontSize: 34,
                },
                pickerLabel: {
                    fontSize: 26,
                    right: -20,
                },
                pickerLabelContainer: {
                    width: 60,
                },
                pickerItemContainer: {
                    width: 150,
                },
            }}
        />
    </View>
)


Props 💅

TimerPicker ⏲️

PropDescriptionTypeDefaultRequired
onDurationChangeCallback when the duration changes(duration: { hours: number, minutes: number, seconds: number }) => void-false
initialValueInitial value for the picker{ hours?: number, minutes?: number, seconds?: number }-false
hideHoursHide the hours pickerBooleanfalsefalse
hideMinutesHide the minutes pickerBooleanfalsefalse
hideSecondsHide the seconds pickerBooleanfalsefalse
hoursPickerIsDisabledDisable the hours picker pickerBooleanfalsefalse
minutesPickerIsDisabledDisable the minutes picker pickerBooleanfalsefalse
secondsPickerIsDisabledDisable the seconds picker pickerBooleanfalsefalse
hourLimitLimit on the hours it is possible to select{ max?: Number, min?: Number }-false
minuteLimitLimit on the minutes it is possible to select{ max?: Number, min?: Number }-false
secondLimitLimit on the seconds it is possible to select{ max?: Number, min?: Number }-false
maximumHoursThe highest value on the hours pickerNumber23false
maximumMinutesThe highest value on the minutes pickerNumber59false
maximumSecondsThe highest value on the seconds pickerNumber59false
hourIntervalThe interval between values on the hours pickerNumber1false
minuteIntervalThe interval between values on the minutes pickerNumber1false
secondIntervalThe interval between values on the seconds pickerNumber1false
hourLabelLabel for the hours pickerString | React.ReactElementhfalse
minuteLabelLabel for the minutes pickerString | React.ReactElementmfalse
secondLabelLabel for the seconds pickerString | React.ReactElementsfalse
padHoursWithZeroPad single-digit hours in the picker with a zeroBooleanfalsefalse
padMinutesWithZeroPad single-digit minutes in the picker with a zeroBooleantruefalse
padSecondsWithZeroPad single-digit seconds in the picker with a zeroBooleantruefalse
padWithNItemsNumber of items to pad the picker with on either sideNumber1false
aggressivelyGetLatestDurationSet to True to ask DurationScroll to aggressively update the latestDuration refBooleanfalsefalse
allowFontScalingAllow font in the picker to scale with accessibility settingsBooleanfalsefalse
use12HourPickerSwitch the hour picker to 12-hour format with an AM / PM labelBooleanfalsefalse
amLabelSet the AM label if using the 12-hour pickerStringamfalse
pmLabelSet the PM label if using the 12-hour pickerStringpmfalse
repeatHourNumbersNTimesSet the number of times the list of hours is repeated in the pickerNumber7false
repeatMinuteNumbersNTimesSet the number of times the list of minutes is repeated in the pickerNumber3false
repeatSecondNumbersNTimesSet the number of times the list of seconds is repeated in the pickerNumber3false
disableInfiniteScrollDisable the infinite scroll featureBooleanfalsefalse
LinearGradientLinear Gradient Componentexpo-linear-gradient.LinearGradient or react-native-linear-gradient.default-false
HapticsHaptics Namespace (required for Haptic feedback)expo-haptics-false
AudioAudio Class (required for audio feedback i.e. click sound)expo-av.Audio-false
pickerFeedbackGeneric picker feedback as alternative to the below Expo feedback support() => void | Promise<void> -false
FlatListFlatList component used internally to implement each picker (hour, minutes and seconds). More info belowreact-native.FlatListFlatList from react-nativefalse
clickSoundAssetCustom sound asset for click sound (required for offline click sound - download default here)require(.../somefolderpath) or {uri: www.someurl}-false
pickerContainerPropsProps for the picker containerReact.ComponentProps<typeof View>-false
pickerGradientOverlayPropsProps for both gradient overlaysPartial<LinearGradientProps>-false
topPickerGradientOverlayPropsProps for the top gradient overlayPartial<LinearGradientProps>-false
bottomPickerGradientOverlayPropsProps for the bottom gradient overlayPartial<LinearGradientProps>-false
stylesCustom styles for the timer pickerCustomTimerPickerStyles-false
Custom Styles 👗

The following custom styles can be supplied to re-style the component in any way. Various styles are applied by default - you can take a look at these here.

Style PropDescriptionType
themeTheme of the component"light" | "dark"
backgroundColorMain background colorstring
textBase text styleTextStyle
pickerContainerMain container for the pickerViewStyle & { backgroundColor?: string }
pickerLabelContainerContainer for the picker's labelsViewStyle
pickerLabelStyle for the picker's labelsTextStyle
pickerAmPmContainerStyle for the picker's labelsViewStyle
pickerAmPmLabelStyle for the picker's labelsTextStyle
pickerItemContainerContainer for each number in the pickerViewStyle & { height?: number }
pickerItemStyle for each individual picker numberTextStyle
disabledPickerItemStyle for any numbers outside any set limitsTextStyle
disabledPickerContainerStyle for disabled pickersViewStyle
pickerGradientOverlayStyle for the gradient overlay (fade out)ViewStyle

Note the minor limitations to the allowed styles for pickerContainer and pickerItemContainer. These are made because these styles are used for internal calculations and all possible backgroundColor/height types are not supported.

Performance

When the disableInfiniteScroll prop is not set, the picker gives the appearance of an infinitely scrolling picker by auto-scrolling forward/back when you near the start/end of the list. When the picker auto-scrolls, a momentary flicker is visible if you are scrolling very slowly.

To mitigate for this, you can modify the repeatHourNumbersNTimes, repeatMinuteNumbersNTimes and repeatSecondNumbersNTimes props. These set the number of times the list of numbers in each picker is repeated. These have a performance trade-off: higher values mean the picker has to auto-scroll less to maintain the infinite scroll, but has to render a longer list of numbers. By default, the props are set to 7, 3 and 3, respectively, which balances that trade-off effectively.

Note that you can avoid the auto-scroll flickering entirely by disabling infinite scroll. You could then set the above props to high values, so that a user has to scroll far down/up the list to reach the end of the list.

Custom FlatList

The library offers the ability to provide a custom component for the <FlatList />, instead of the default React Native component. This allows for more flexibility and integration with libraries like react-native-gesture-handler or other components built on top of it, like https://ui.gorhom.dev/components/bottom-sheet.

E.g. if you want to place the timer picker within that bottom-sheet component, the scrolling detection from the bottom-sheet would interfere with the one inside the timer picker, but it can be easily solved by providing the FlatList component from react-native-gesture-handler like this:

import { FlatList } from 'react-native-gesture-handler';
import { TimerPicker } from "react-native-timer-picker";

// ...

<TimerPicker
    {...props}
    FlatList={FlatList}
/>

Important: The custom component needs to have the same interface as React Native's <FlatList /> in order for it to work as expected. A complete reference of the current usage can be found here

Generic feedback

To enable haptic feedback from the non-Expo module react-native-haptic-feedback or provide feedback in any other form you can use the generic feedback callback prop pickerFeedback. This function is called whenever any of the pickers tick onto a new number.

import { trigger } from 'react-native-haptic-feedback';
import { TimerPicker } from "react-native-timer-picker";

// ...

<TimerPicker
    {...props}
    pickerFeedback={() => trigger('impactLight')}
/>

TimerPickerModal ⏰

The TimerPickerModal component accepts all TimerPicker props, and the below additional props.

PropDescriptionTypeDefaultRequired
visibleDetermines if the modal is visibleBoolean-true
setIsVisibleCallback to set modal visibility(isVisible: boolean) => void-true
onConfirmCallback when the user confirms the selected time({ hours, minutes, seconds }: { hours: number, minutes: number, seconds: number }) => void-true
onCancelCallback when the user cancels the selection() => void-false
closeOnOverlayPressDetermines if the modal should close on overlay pressBooleanfalsefalse
hideCancelButtonHide the cancel button within the modalBooleanfalsefalse
confirmButtonTextText for the confirm buttonStringConfirmfalse
cancelButtonTextText for the cancel buttonStringCancelfalse
modalTitleTitle text for the modalString-false
modalPropsProps for the main modal componentReact.ComponentProps<typeof Modal>-false
containerPropsProps for the main containerReact.ComponentProps<typeof View>-false
contentContainerPropsProps for the content containerReact.ComponentProps<typeof View>-false
buttonContainerPropsProps for the button containersReact.ComponentProps<typeof View>-false
buttonTouchableOpacityPropsProps for the button touchable opacitiesReact.ComponentProps<typeof TouchableOpacity>-false
modalTitlePropsProps for the modal title text componentReact.ComponentProps<typeof Text>-false
stylesCustom styles for the timer picker modalCustomTimerPickerModalStyles-false
Custom Styles 👕

The following custom styles can be supplied to re-style the component in any way. You can also supply all of the styles specified in CustomTimerPickerStyles. Various styles are applied by default - you can take a look at these here.

Style PropDescriptionType
containerMain container's styleViewStyle
contentContainerStyle for the content's containerViewStyle
buttonContainerStyle for the container around the buttonsViewStyle
buttonGeneral style for both buttonsTextStyle
cancelButtonStyle for the cancel buttonTextStyle
confirmButtonStyle for the confirm buttonTextStyle
modalTitleStyle for the title of the modalTextStyle

Methods 🔄

TimerPicker

The library exposes a TimerPickerRef type, which can be used to type your ref to the picker:

const timerPickerRef = useRef < TimerPickerRef > null;

It has the following available methods:

reset - imperative method to reset the selected duration to their initial values.

timerPickerRef.current.reset(options?: { animated: boolean });

setValue - imperative method to set the selected duration to a particular value

timerPickerRef.current.setValue({ hours: number, minutes: number, seconds: number }, options?: { animated: boolean });

It also exposes the following ref object:

latestDuration - provides access to the latest duration (even during scrolls). This only works if aggressivelyGetLatestDuration is set to True (as in TimerPickerModal). It is used internally to ensure that the latest duration is returned in TimerPickerModal on pressing the confirm button, even if the inputs are still scrolling.

const latestDuration = timerPickerRef.current?.latestDuration;
const newDuration = {
    hours: latestDuration?.hours?.current,
    minutes: latestDuration?.minutes?.current,
    seconds: latestDuration?.seconds?.current,
};

TimerPickerModal

An identical ref is also exposed for the TimerPickerModal component.


Contributing 🧑‍🤝‍🧑

Contributions to this project are more than welcome.

Dev Setup

To get this project running locally:

  1. Clone the Git repo.
  2. Run yarn setup from the project root (this installs the project dependencies and the examples' additional dependencies)

You can then start either the Expo example or the bare React Native example:

  • For Expo, run yarn start to start the Expo example in Expo Go.
  • For bare React Native, run yarn start-bare:android or start-bare:ios to start the project on an emulator/device.

GitHub Guidelines

There are two permenant branches: main and develop. You should never work directly on either of these branches.

  1. Create a new branch off develop for your work using the pattern feature/{DESCRIPTION}.
  2. When you think your work is ready for review, submit a PR from your branch back to develop.
  3. Once the PR is resolved, your work will be merged into develop, and will be included in the next major/minor release.

Limitations ⚠

The project is not compatibile with React Native versions prior to v0.72.0 due to this React Native issue.


License 📝

This project is licensed under the MIT License.

Keywords

FAQs

Package last updated on 18 Nov 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc