---
title: "React Select Setting values Example | Mobiscroll"
component: "Select"
framework: "React"
library_version: "6.1.5"
url: "https://demo.mobiscroll.com/react/select/setting-values-defaults"
---

# Setting values - React Select demo

React Select scroller demo with examples for programmatically setting values and defaults for single/multiple select. For React and Next.JS.

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

## Description

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

## What this demo shows

- Three groups of Select examples demonstrate how to initialize, change, and confirm selected values.
- **Controlling the default value** The first example starts with no selected value. The second uses the `defaultSelection` option to highlight an initial value when the picker opens; the user must confirm it before it becomes the selected value.
- **Setting values at runtime** An inline Select displays the picker directly on the page without an input. The Boston and London buttons above it use the `setVal` method to change the value programmatically, while the value can still be changed through the Select UI.
- **Setting values with buttons** The first example adds a custom button between the Cancel and Set buttons in the picker header. The second shows only a Cancel button in the footer and applies a value automatically when the user selects it, closing the dialog without requiring a separate Set action.
- **Select inputs** Focusing or clicking an input opens its picker below the input. Clicking outside the picker closes it.
- **Picker content** Input-based examples display a predefined list of options in a dropdown-style popup, while the inline example displays the options directly on the page.
- **Hover state** Hovering over an option highlights it.
- **Selection** Selecting an option marks it with a checkmark to indicate the current value.
- **Input value** In the input-based examples, confirming a selection updates the associated input with that value.

## Best for

- **Optional form fields** Start with no selected value when users should make an explicit choice.
- **Suggested defaults** Present a preselected option while requiring users to confirm it before applying the value.
- **External controls** Update a Select programmatically from preset buttons or other controls outside the component.
- **Inline selection** Keep a small set of options visible on the page when opening a separate popup would interrupt the workflow.
- **Explicit confirmation** Use Cancel and Set actions when users should review a choice before applying it.
- **Immediate selection** Remove the Set action when choosing an option should apply the value and close the dialog immediately.
- **Custom picker actions** Add a custom button when the selection flow needs a dedicated shortcut alongside the standard actions.

## Tutorial

### Controlling the default value

The select has no selected value by default. You can however manually set a default value through the [`defaultSelection`](https://mobiscroll.com/docs/react/select/api#opt-defaultSelection) option. This value will show as selected when opening the control, but it needs to be submitted to be accepted as a selected value.

```jsx
const myData = [
    { text: 'Atlanta', value: 'atl' },
    { text: 'Berlin', value: 'ber' },
    { text: 'Boston', value: 'bos' },
    { text: 'Chicago', value: 'chi' },
    { text: 'London', value: 'lon' }
];

<Select
    data={myData}
/>
```

```jsx
const myData = [
    { text: 'Atlanta', value: 'atl' },
    { text: 'Berlin', value: 'ber' },
    { text: 'Boston', value: 'bos' },
    { text: 'Chicago', value: 'chi' },
    { text: 'London', value: 'lon' }
];

const myDefault = 'ber';

<Select
    data={myData}
    defaultSelection={myDefault}
/>
```

### Setting values runtime

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

```jsx
const [myValue, setMyValue] = React.useState(null);
const setBoston = (event) => {
    setMyValue('bos');
};
const setLondon = (event) => {
    setMyValue('lon');
};

<Button onClick={setBoston}>Boston</Button>
<Button onClick={setLondon}>London</Button>
<Select
    data={myData}
    value={myValue}
/>
```

### Setting values with buttons

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

```jsx
const myData = [
    { text: 'Atlanta', value: 'atl' },
    { text: 'Berlin', value: 'ber' },
    { text: 'Boston', value: 'bos' },
    { text: 'Chicago', value: 'chi' },
    { text: 'London', value: 'lon' }
];
const myRef = React.useRef();
const customButtons = React.useMemo(() => {
    return [{
            text: 'Custom',
            handler: () => {
                myRef.current.setTempVal('chi');
            }
        }, 'set', 'cancel'
    ]
}, []);
                            
<Select
    data={myData}
    buttons={customButtons}
    ref={myRef}
/>
```

```jsx
const myData = [
    { text: 'Atlanta', value: 'atl' },
    { text: 'Berlin', value: 'ber' },
    { text: 'Boston', value: 'bos' },
    { text: 'Chicago', value: 'chi' },
    { text: 'London', value: 'lon' }
];
                            
<Select
    data={myData}
    buttons={['cancel']}
/>
```

## API used in this demo

- [`theme`](https://mobiscroll.com/docs/react/select/api#opt-theme) - option
- [`themeVariant`](https://mobiscroll.com/docs/react/select/api#opt-themeVariant) - option
- [`setTempVal`](https://mobiscroll.com/docs/react/select/api#method-setTempVal) - method
- [`inputStyle`](https://mobiscroll.com/docs/react/select/api#opt-inputStyle) - option
- [`labelStyle`](https://mobiscroll.com/docs/react/select/api#opt-labelStyle) - option
- [`data`](https://mobiscroll.com/docs/react/select/api#opt-data) - option
- [`label`](https://mobiscroll.com/docs/react/select/api#opt-label) - option
- [`inputProps`](https://mobiscroll.com/docs/react/select/api#opt-inputProps) - option
- [`defaultSelection`](https://mobiscroll.com/docs/react/select/api#opt-defaultSelection) - option
- [`display`](https://mobiscroll.com/docs/react/select/api#opt-display) - option
- [`buttons`](https://mobiscroll.com/docs/react/select/api#opt-buttons) - option

## Code

### JSX

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

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

function App() {
  const [customSelected, setCustomSelected] = useState();
  const selectRef = useRef();

  const myData = useMemo(
    () => [
      {
        text: 'Atlanta',
        value: 'atl',
      },
      {
        text: 'Berlin',
        value: 'ber',
      },
      {
        text: 'Boston',
        value: 'bos',
      },
      {
        text: 'Chicago',
        value: 'chi',
      },
      {
        text: 'London',
        value: 'lon',
      },
    ],
    [],
  );

  const customButtons = useMemo(
    () => [
      {
        text: 'Custom',
        handler: () => {
          selectRef.current.setTempVal('chi');
        },
      },
      'set',
      'cancel',
    ],
    [],
  );

  const inputProps = useMemo(
    () => ({
      inputStyle: 'outline',
      labelStyle: 'stacked',
      placeholder: 'Please select...',
    }),
    [],
  );

  const setBoston = useCallback(() => {
    setCustomSelected('bos');
  }, []);

  const setLondon = useCallback(() => {
    setCustomSelected('lon');
  }, []);

  return (
    <>
      <div className="mbsc-form-group">
        <div className="mbsc-form-group-title">Controlling the default value</div>
        <Select data={myData} label="Default" inputProps={inputProps} />
        <Select data={myData} label="Custom default" inputProps={inputProps} defaultSelection="ber" />
      </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={setBoston}>Boston</Button>
          <Button onClick={setLondon}>London</Button>
        </div>
        <Select data={myData} display="inline" value={customSelected} />
      </div>
      <div className="mbsc-form-group">
        <div className="mbsc-form-group-title">Buttons API</div>
        <Select data={myData} ref={selectRef} label="Custom" inputProps={inputProps} buttons={customButtons} />
        <Select data={myData} label="Auto set" inputProps={inputProps} buttons={['cancel']} />
      </div>
    </>
  );
}

export default App;
```

### TSX

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

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

const myData = [
  {
    text: 'Atlanta',
    value: 'atl',
  },
  {
    text: 'Berlin',
    value: 'ber',
  },
  {
    text: 'Boston',
    value: 'bos',
  },
  {
    text: 'Chicago',
    value: 'chi',
  },
  {
    text: 'London',
    value: 'lon',
  },
];

const App: FC = () => {
  const [customSelected, setCustomSelected] = useState<string>('');
  const selectRef = useRef<Select | null>(null);

  const customButtons = useMemo<(string | MbscPopupButton)[]>(
    () => [
      {
        text: 'Custom',
        handler: () => {
          selectRef.current!.setTempVal('chi');
        },
      },
      'set',
      'cancel',
    ],
    [],
  );

  const inputProps = useMemo(
    () => ({
      inputStyle: 'outline',
      labelStyle: 'stacked',
      placeholder: 'Please select...',
    }),
    [],
  );

  const setBoston = useCallback(() => {
    setCustomSelected('bos');
  }, []);

  const setLondon = useCallback(() => {
    setCustomSelected('lon');
  }, []);

  return (
    <>
      <div className="mbsc-form-group">
        <div className="mbsc-form-group-title">Controlling the default value</div>
        <Select data={myData} label="Default" inputProps={inputProps} />
        <Select data={myData} label="Custom default" inputProps={inputProps} defaultSelection="ber" />
      </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={setBoston}>Boston</Button>
          <Button onClick={setLondon}>London</Button>
        </div>
        <Select data={myData} display="inline" value={customSelected} />
      </div>
      <div className="mbsc-form-group">
        <div className="mbsc-form-group-title">Buttons API</div>
        <Select data={myData} ref={selectRef} label="Custom" inputProps={inputProps} buttons={customButtons} />
        <Select data={myData} label="Auto set" inputProps={inputProps} buttons={['cancel']} />
      </div>
    </>
  );
};
export default App;
```

## Implementation notes

- `data` is an array of `{ text, value }` objects (e.g. `{ text: 'Atlanta', value: 'atl' }`) that defines the option list; it is the same shape whether the select is input-based or `display: 'inline'`.
- With no `defaultSelection` set, the select's value starts as `null`/unselected and the input shows the `placeholder` text.
- `defaultSelection` takes a `value` from `data` (e.g. `'ber'`) and pre-highlights that option when the picker opens; it does not set the committed value until the user confirms it (via the `set`/default confirm action).
- `display: 'inline'` renders the option list directly on the page instead of behind an input-triggered popup; it is combined with a `height` (e.g. `300`) to make the list scrollable within a fixed area.
- The `.setVal(value)` instance method sets the selected value programmatically at runtime, independent of `defaultSelection` - the demo calls it from external button click handlers (e.g. `.setVal('bos')`, `.setVal('lon')`).
- The `.setTempVal(value)` instance method stages a value into the (not-yet-confirmed) temporary selection without committing it - used from a custom `buttons` handler so the value still requires the `set`/confirm action (or auto-set) to apply.
- `buttons` is an array mixing predefined action strings (`'set'`, `'cancel'`) and custom button objects `{ text, handler }`; a custom entry is inserted between the predefined ones to add a dedicated action (e.g. `{ text: 'Custom', handler: () => instance.setTempVal('chi') }`).
- Omitting `'set'` from `buttons` (e.g. `buttons: ['cancel']`) switches the picker to auto-set behavior: selecting an option applies the value and closes the popup immediately, without a separate confirm step.
- Per framework, programmatic value control differs: JS/jQuery call `.setVal(value)` / `.setTempVal(value)` on the instance (JS: captured directly from the return value of `mobiscroll.select(...)`; jQuery: obtained via `.mobiscroll('getInst')`); React drives value via a `value` prop bound to component state (`useState`) updated from button `onClick` handlers, and reads/sets a `ref` (`selectRef.current!.setTempVal(...)`) for the buttons-API case; Vue binds `v-model` to a `ref()` for the runtime-value case, and accesses `customRef.value.instance.setTempVal(...)` for the buttons-API case; Angular binds `[(ngModel)]` to a component property for the runtime-value case, and calls `.setTempVal(...)` through a `@ViewChild` reference to the `<mbsc-select>` for the buttons-API case.

## 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: [Multi level hierarchy](https://demo.mobiscroll.com/react/select/linked-hierarchical-pickers.md) - React hierarchical select example. Dynamically populate linked lists based on previous selection.
