---
title: "React Calendar Programmatic Value Control Example | Mobiscroll"
component: "Calendar"
framework: "React"
library_version: "6.1.5"
url: "https://demo.mobiscroll.com/react/calendar/setting-values-defaults"
---

# Programmatic Value Control - React Calendar demo

Set a default date or update the React date picker value programmatically — via bound state or custom buttons. For React and Next.JS.

- [Live demo](https://demo.mobiscroll.com/react/calendar/setting-values-defaults)
- [View React JS code on GitHub](https://github.com/acidb/mobiscroll-demos-react/tree/main/src/demos/datepicker/calendar/setting-values-defaults)
- [View React TS code on GitHub](https://github.com/acidb/mobiscroll-demos-react-ts/tree/main/src/demos/datepicker/calendar/setting-values-defaults)
- This demo in other frameworks: [JavaScript](https://demo.mobiscroll.com/javascript/calendar/setting-values-defaults.md), [jQuery](https://demo.mobiscroll.com/jquery/calendar/setting-values-defaults.md), [Angular](https://demo.mobiscroll.com/angular/calendar/setting-values-defaults.md), [Vue](https://demo.mobiscroll.com/vue/calendar/setting-values-defaults.md)

## Description

Values can change in a couple of different ways: through defaults, interacting with the UI or programmatically. The date and time picker defaults to `now`, which can be easily overridden with the [`defaultSelection`](https://mobiscroll.com/docs/react/datepicker/api#opt-defaultSelection) option. The values are set by interacting with the component and making a selection or it can be done programmatically by updating the bound value. Use the [`buttons`](https://mobiscroll.com/docs/react/datepicker/api#opt-buttons) option for showing/hiding `set`, `cancel` or add custom buttons.

## What this demo shows

- Three example groups demonstrate how to control a monthly date picker value through defaults, runtime updates, and action buttons.
- **Header navigation** The month and year label opens the month and year picker, while the previous and next arrow buttons navigate between months.
- **Month view** A fixed weekday header displays abbreviated day names from Sunday through Saturday, with dates arranged in a grid below.
- **Month navigation** Users can navigate between months by dragging the calendar left or right.
- **Day cell states** Hovering over a date adds a gray highlight, while selecting a date adds a blue highlight. The current date remains highlighted when another date is selected.
- **Adjacent months** Dates from the previous and next months use a muted style. Selecting one navigates to its corresponding month.
- **Footer actions** In the input-based examples, Cancel discards the change and Set confirms the selected date.
- **Input value** Confirming a date displays it in the input using a month, day, and year format.
- **Default values** The first example group compares the default behavior with a Datepicker initialized to a specific value through the `defaultSelection` option.
- **Runtime values** The second example group combines interactive selection with programmatic updates. Two external buttons set a specific date or return the Datepicker to the current date.
- **Button-based values** The third example group demonstrates the button API with three configurations: a Now button that selects the current date, a custom button that selects a predefined date, and automatic value confirmation with the Set button removed.

## Best for

- **Preselected dates** Initialize a Datepicker with a meaningful default, such as a previously saved date or a suggested appointment date.
- **External controls** Update the selected date from controls outside the Datepicker, such as date shortcuts, reset actions, or workflow navigation.
- **Date shortcuts** Provide one-click actions for commonly used values, including the current date or a predefined date.
- **Automatic confirmation** Apply a date immediately after selection in workflows where a separate Set action is unnecessary.

## Tutorial

### Controlling the default value

The calendar defaults to today if not overridden. You can however manually set a default value through the [`defaultSelection`](https://mobiscroll.com/docs/react/datepicker/api#opt-defaultSelection) option.

```jsx
<Datepicker
    controls={['calendar']}
/>
```

```jsx
const defaultSelection = new Date(2020, 11, 24);
                           
<Datepicker
    controls={['calendar']}
    defaultSelection={defaultSelection}
/>
```

### Setting values runtime

While the selected value can be changed by interacting with the calendar, you can set the model value to change it programmatically.

```jsx
const [val, setVal] = React.useState(null);
const setValue = (event) => {
    setVal(new Date(2020, 0, 2));
};
const setToday = (event) => {
    setVal(new Date());
};

<Button onClick={setValue}>02-01-2020</Button>
<Button onClick={setToday}>Today</Button>
<Datepicker
    controls={['calendar']}
    value={val}
/>
```

### Setting values with buttons

The button API provides shortcuts to value selection and confirmation. Add 'Now' or custom button to the component or entirely remove the 'Set' button to activate auto-set, which automatically closes the dialog if a date is selected.

```jsx
const [now, setNow] = React.useState();
const nowButtons = React.useMemo(() => {
    return [{
        text: 'Now',
        handler: () => {
            now.setVal(new Date());
            now.close();
        }
    }, 'set', 'cancel'];
}, [now]);
                            
<Datepicker
    controls={['calendar']}
    buttons={nowButtons}
    ref={setNow}
/>
```

```jsx
const [custom, setCustom] = React.useState();
const customButtons = React.useMemo(() => {
    return [{
            text: '05 Jan 2020',
            handler: () => {
                custom.setVal(new Date(2020, 0, 5));
                custom.close();
            }
        }, 'set', 'cancel'
    ];
}, [custom]);
                            
<Datepicker
    controls={['calendar']}
    buttons={customButtons}
    ref={setCustom}
/>
```

```jsx
const autoButtons = React.useMemo(() => {
    return [{
        text: 'Close',
        handler: 'cancel'
    }];
}, []);
                            
<Datepicker
    controls={['calendar']}
    buttons={autoButtons}
/>
```

## API used in this demo

- [`theme`](https://mobiscroll.com/docs/react/datepicker/api#opt-theme) - option
- [`themeVariant`](https://mobiscroll.com/docs/react/datepicker/api#opt-themeVariant) - option
- [`defaultSelection`](https://mobiscroll.com/docs/react/datepicker/api#opt-defaultSelection) - option
- [`display`](https://mobiscroll.com/docs/react/datepicker/api#opt-display) - option
- [`buttons`](https://mobiscroll.com/docs/react/datepicker/api#opt-buttons) - option
- [`controls`](https://mobiscroll.com/docs/react/datepicker/api#opt-controls) - option

## Code

### JSX

```jsx
import { Button, Datepicker, Page, setOptions } from '@mobiscroll/react';
import { useCallback, useMemo, useState } from 'react';

setOptions({
  theme: 'ios',
  themeVariant: 'light'
});

function App() {
  const initialValue = new Date(2020, 11, 24);

  const [now, setNow] = useState();
  const [custom, setCustom] = useState();
  const [val, setVal] = useState();

  const nowButtons = useMemo(
    () => [
      {
        text: 'Now',
        handler: () => {
          now.setVal(new Date());
          now.close();
        },
      },
      'set',
      'cancel',
    ],
    [now],
  );

  const customButtons = useMemo(
    () => [
      {
        text: '05 Jan 2020',
        handler: () => {
          custom.setVal(new Date(2020, 0, 5));
          custom.close();
        },
      },
      'set',
      'cancel',
    ],
    [custom],
  );

  const autoButtons = useMemo(
    () => [
      {
        text: 'Close',
        handler: 'cancel',
      },
    ],
    [],
  );

  const setValue = useCallback(() => {
    setVal(new Date(2020, 0, 2));
  }, []);

  const setToday = useCallback(() => {
    setVal(new Date());
  }, []);

  return (
    <Page>
      <div className="mbsc-form-group">
        <div className="mbsc-form-group-title">Controlling the default value</div>
        <Datepicker label="Default" placeholder="Please select..." />
        <Datepicker label="Custom default" defaultSelection={initialValue} placeholder="Please select..." />
      </div>
      <div className="mbsc-form-group">
        <div className="mbsc-form-group-title">Setting a custom value</div>
        <div className="mbsc-button-group-block">
          <Button onClick={setValue}>02-01-2020</Button>
          <Button onClick={setToday}>Today</Button>
        </div>
        <Datepicker display="inline" value={val} />
      </div>

      <div className="mbsc-form-group">
        <div className="mbsc-form-group-title">Buttons API</div>
        <Datepicker buttons={nowButtons} ref={setNow} label="Now" placeholder="Please select..." />
        <Datepicker buttons={customButtons} ref={setCustom} label="Custom" placeholder="Please select..." />
        <Datepicker buttons={autoButtons} label="Auto set" placeholder="Please select..." />
      </div>
    </Page>
  );
}

export default App;
```

### TSX

```tsx
import { Button, Datepicker, MbscPopupButton, Page, setOptions } from '@mobiscroll/react';
import { FC, useCallback, useMemo, useState } from 'react';

setOptions({
  theme: 'ios',
  themeVariant: 'light'
});

const initialValue = new Date(2020, 11, 24);

const App: FC = () => {
  const [now, setNow] = useState<Datepicker | null>(null);
  const [custom, setCustom] = useState<Datepicker | null>(null);
  const [val, setVal] = useState<Date>();

  const nowButtons = useMemo<(string | MbscPopupButton)[]>(
    () => [
      {
        text: 'Now',
        handler: () => {
          now!.setVal(new Date());
          now!.close();
        },
      },
      'set',
      'cancel',
    ],
    [now],
  );

  const customButtons = useMemo<(string | MbscPopupButton)[]>(
    () => [
      {
        text: '05 Jan 2020',
        handler: () => {
          custom!.setVal(new Date(2020, 0, 5));
          custom!.close();
        },
      },
      'set',
      'cancel',
    ],
    [custom],
  );

  const autoButtons = useMemo<(string | MbscPopupButton)[]>(
    () => [
      {
        text: 'Close',
        handler: 'cancel',
      },
    ],
    [],
  );

  const setValue = useCallback(() => {
    setVal(new Date(2020, 0, 2));
  }, []);

  const setToday = useCallback(() => {
    setVal(new Date());
  }, []);

  return (
    <Page>
      <div className="mbsc-form-group">
        <div className="mbsc-form-group-title">Controlling the default value</div>
        <Datepicker label="Default" controls={['calendar']} placeholder="Please select...">
          Default
        </Datepicker>
        <Datepicker label="Custom default" controls={['calendar']} defaultSelection={initialValue} placeholder="Please select...">
          Custom default
        </Datepicker>
      </div>
      <div className="mbsc-form-group">
        <div className="mbsc-form-group-title">Setting a custom value</div>
        <div className="mbsc-button-group-block">
          <Button onClick={setValue}>02-01-2020</Button>
          <Button onClick={setToday}>Today</Button>
        </div>
        <Datepicker controls={['calendar']} display="inline" value={val} />
      </div>

      <div className="mbsc-form-group">
        <div className="mbsc-form-group-title">Buttons API</div>
        <Datepicker controls={['calendar']} buttons={nowButtons} ref={setNow} label="Now" placeholder="Please select..."></Datepicker>
        <Datepicker
          controls={['calendar']}
          buttons={customButtons}
          ref={setCustom}
          label="Custom"
          placeholder="Please select..."
        ></Datepicker>
        <Datepicker controls={['calendar']} buttons={autoButtons} label="Auto set" placeholder="Please select...">
          Auto set
        </Datepicker>
      </div>
    </Page>
  );
};
export default App;
```

## Implementation notes

- Use `controls: ['calendar']`. Without any value option set, the picker defaults to today.
- Set `defaultSelection` to a `Date`/date string to change the initial value shown before the user makes a selection (e.g. `defaultSelection: new Date(2020, 11, 24)`).
- The value can be updated programmatically from outside the picker: in React, set the `value` prop from component state; in Angular/Vue, assign to the `[(ngModel)]`/`v-model`-bound variable; in JS/jQuery, call `instance.setVal(date)` imperatively on the picker instance.
- Customize the footer with `buttons`, an array mixing custom button objects (`{ text: 'Now', handler: function () { inst.setVal(new Date()); inst.close(); } }`) with built-in string tokens - the predefined tokens are `'ok'`, `'set'`, `'cancel'`, and `'close'` (default `['set', 'cancel']`) - a custom button's `handler` can also be one of these strings as shorthand instead of a function, e.g. `handler: 'cancel'` to just close the picker.
- A `buttons` array containing only a single close-style button (e.g. `[{ text: 'Close', handler: 'cancel' }]`, or the built-in `['close']` token alone) effectively auto-confirms the picker's live selection without a separate "Set" step, since there's no button left to discard the change.

## Run it in your project

1. If not signed up yet, or don't own a license, you can [start a free trial](https://mobiscroll.com/starttrial).

2. Clone the repository:

   ```
   git clone https://github.com/acidb/mobiscroll-demos-react.git
   ```

3. If not installed yet, install the Mobiscroll CLI from NPM:

   ```
   npm install -g @mobiscroll/cli
   ```

4. Config Mobiscroll - open a terminal window in the root directory and run:

   ```
   mobiscroll config react
   ```

5. Install dependencies - open a terminal window in the root directory and run:

   ```
   npm install
   ```

6. Run the project:

   ```
   npm run dev
   ```

On a trial, add `--trial` to the config command: `mobiscroll config react --trial`.

Running a demo locally requires a Mobiscroll trial or a license; setup is per framework at https://mobiscroll.com/docs/react/getting-started/installation

## Related demos

- Previous: [Formatting Values](https://demo.mobiscroll.com/react/calendar/formatting-return-values.md) - Customize how dates and times appear in React date picker inputs — set custom date and time formats or inherit them from locale settings.
- Next: [Timezone Configuration](https://demo.mobiscroll.com/react/calendar/setting-the-picker-timezone.md) - Configure data and display timezones in the React date picker — with Luxon, Day.js, or moment-timezone.
