Giter VIP home page Giter VIP logo

dgreasi / react-native-time-slot-picker Goto Github PK

View Code? Open in Web Editor NEW
15.0 1.0 4.0 3.97 MB

A simple UI library to pick a time slot for a selected day.

Home Page: https://www.npmjs.com/package/@dgreasi/react-native-time-slot-picker

License: MIT License

JavaScript 9.02% TypeScript 90.98%
picker react-native slot time time-slot-booking time-slots timeslot timeslots time-slot time-slot-picker

react-native-time-slot-picker's Introduction

react-native-time-slot-picker

NPM version npm npm npm runs with expo

Features

  • No dependencies.
  • A time slot picker for react native.
  • Pass the availableDates you want to show.
  • Pick a day and the timeslot you wish.
  • Simple UX.
  • Use colors of your preference by using the params.
  • Use day shortnames and month names of your preference by using the params.
  • Change the title of the timeslots section by using the params.
  • Change the width of timeslot element by using the params.

Table of contents

Screenshots

You can test the library by opening the following snack here.

Run example locally

git clone https://github.com/dgreasi/react-native-time-slot-picker.git
cd react-native-time-slot-picker
npm i # or `yarn`
npm run example ios # or `yarn example ios`

Installation

npm i @dgreasi/react-native-time-slot-picker
# OR
yarn add @dgreasi/react-native-time-slot-picker

Usage

import * as React from 'react';
import { SafeAreaView, StatusBar } from 'react-native';
import {
  IAppointment,
  IAvailableDates,
  TimeSlotPicker,
} from '@dgreasi/react-native-time-slot-picker';
import { useEffect, useState } from 'react';

const availableDates: IAvailableDates[] = [
  {
    date: '2023-08-17T21:00:00.000Z', // new Date().toISOString()
    slotTimes: ['08:00-09:00', '09:00-10:00'], // Array<string> of time slots
  },
  {
    date: '2023-08-18T21:00:00.000Z',
    slotTimes: [], // No availability
  },
  {
    date: '2023-08-19T21:00:00.000Z',
    slotTimes: ['08:00-09:00', '09:00-10:00'],
  },
];

export default function App() {
  const [dateOfAppointment, setDateOfAppointment] =
    useState<IAppointment | null>(null);

  useEffect(() => {
    // Contains the selected date, time slot in the following format
    // {"appointmentDate": "2023-08-17T21:00:00.000Z", "appointmentTime": "18:00-19:00"}
    console.log('Date of appointment updated: ', dateOfAppointment);
  }, [dateOfAppointment]);

  return (
    <SafeAreaView>
      <StatusBar backgroundColor="transparent" barStyle="dark-content" />
      <TimeSlotPicker
        availableDates={availableDates}
        setDateOfAppointment={setDateOfAppointment}
      />
    </SafeAreaView>
  );
}

You can find a detailed example here.

Props

Prop name Description Type Default
setDateOfAppointment A component to use on top of header image. It can also be used without header image to render a custom component as header. (data: IAppointment | null) => void REQUIRED
availableDates The array of the available slot times per date. IAvailableDates[] fixedAvailableDates
scheduledAppointment An already existed appointment, which is going to mark the specific date as with appointment. IAppointment undefined
marginTop Margin top for the whole component. number 0
datePickerBackgroundColor Background color of the section with the horizontal scroll, which contains the days. hex string '#FFFFFF'
timeSlotsBackgroundColor Background color of the section that contains the time slots. hex string '#FFFFFF'
timeSlotsTitle Title of section that contains the string 'Select time'
mainColor Main color of the time slot picker hex string '#04060A'
timeSlotWidth Time slot pill width number 96
dayNamesOverride Day string array to override letters for each Calendar day. First day is Sunday. string[] ['S', 'M', 'T', 'W', 'T', 'F', 'S']
monthNamesOverride Month string array to override default month names that are used as title. string[] ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

Interfaces

Name Description
IAvailableDates { date: string, slotTimes: string[] }
IAppointment { appointmentDate: string, appointmentTime: string }

Roadmap

  • Update scheduledAppointment arg to accept multiple appointments.
  • Update logic of getAppointmentDay() to show dot in dates.
  • Merge providers for performance improvement.

License

MIT

react-native-time-slot-picker's People

Contributors

dgreasi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

react-native-time-slot-picker's Issues

Passing in availableDates causes infinite rendering problem

Whenever I pass in available dates to TimeSlotPicker, I get an infinite rendering issue:

const generateTimeIntervals = (
  start: string,
  end: string,
  duration: number
): string[] => {
  const startTime = new Date(`2000-01-01T${start}`);
  const endTime = new Date(`2000-01-01T${end}`);
  const intervals: string[] = [];

  while (startTime < endTime) {
    const endTimeInterval = new Date(
      Math.min(startTime.getTime() + duration * 60 * 1000, endTime.getTime())
    );

    if (endTimeInterval < endTime) {
      const formattedInterval = `${formatTime(startTime)}-${formatTime(
        endTimeInterval
      )}`;
      intervals.push(formattedInterval);
    }

    startTime.setTime(endTimeInterval.getTime());
  }

  return intervals;
};

const formatTime = (date: Date): string => {
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");
  return `${hours}:${minutes}`;
};

const getNextDays = (daysToAdd: number, currentDate = new Date()) => {
  const nextDate = new Date(currentDate);
  nextDate.setDate(currentDate.getDate() + daysToAdd);
  return nextDate;
};

const DateTimeSlotPicker = (props: ITimeSlotProps) => {
  const { duration, onAppointmentScheduled, onAppointmentConfirmed } = props;

  const startTime = "8:00";
  const endTime = "19:00";

  const durationIntervals = generateTimeIntervals(startTime, endTime, duration);
  const availableDates: IAvailableDates[] = [];

  for (let i = 0; i < 20; i++) {
    const day = {
      date: getNextDays(i).toISOString(),
      slotTimes: durationIntervals,
    };
    availableDates.push(day);
  }

  console.log(availableDates);
  return (
    <View style={styles.container}>
      <TimeSlotPicker
        // availableDates={availableDates}
        setDateOfAppointment={(appointment) =>
          onAppointmentScheduled(appointment)
        }
      />
      <Button
        title="Confirm Time"
        onPress={() => onAppointmentConfirmed(true)}
      />
    </View>
  );
};

I've verified that the format for available dates is correct. What's going on here?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.