Ionic React Picker Example
Tags: javascript, react, ionic, tutorial
Published: 2020-03-01 00:01:18

##Overview
This is a sample [Ionic ReactJS](https://ionicframework.com/docs/react) Application using the [IonPicker Component](https://ionicframework.com/docs/api/picker#properties) derived from plain javascript example provided in the [Ionic Framework Picker Documentation](https://github.com/ionic-team/ionic-docs/blob/master/src/demos/api/picker/index.html).

We also use [React Hooks](https://reactjs.org/docs/hooks-state.html) to manage the state and the example is based off of the Ionic ReactJS Template so we are supporting Typescript.

##Setting Up The Component

```react
import React from "react";
import { PickerColumn } from "@ionic/core";
import { IonPicker } from "@ionic/react";

/**
 * the component has three properties that are defined in this 
 * interface since we are using typescript
 */
interface _Props {
  isOpen : boolean
  onSave : Function
  onCancel : Function
}

const MyPicker: React.FC<_Props> = ({onSave, onCancel, isOpen}) => { 
  return <div></div>
}
```
Picker properties that will be handled
- `onSave`, when the user selects the options from the picker, the `onSave` method will be called to return the values that are selected.
- `onCancel`, when the `onCancel` is selected, no actions are taking inside of the component in this example
- `isOpen`, a property that is passed into the component to let the component determine if it should be visible

## What the Picker Will Render
<img src="https://dev-to-uploads.s3.amazonaws.com/i/68mhad4rzs3gf2yr0d66.png" width="400">
Setting up the two columns of data for the picker component. Since this component will allow the user to select the day of the week and the session time of morning or afternoon
```javascript
const DayColumn = {
  name: "Day",
  options: [
    { text: "Monday", value: "Monday" },
    { text: "Tuesday", value: "Tuesday" },
    { text: "Wednesday", value: "Wednesday" },
    { text: "Thursday", value: "Thursday" },
    { text: "Friday", value: "Friday" }
  ]
} as PickerColumn;;
```
```javascript
const SessionTimeColumn = {
  name: "SessionTime",
  options: [
    { text: "Morning 8a - 12p", value: "Morning" },
    { text: "Afteroon 1p - 5p", value: "Afteroon" }
  ]
} as PickerColumn;
```


##Rendering the Picker Component Content
We use the `IonPicker` Component and pass it the appropriate properties. `isOpen` which is passed in from the parent component. The `columns` are the constants we created above `DayColumn` and `SessionTimeColumn` and then finally the `buttons` for the available actions the user can take.

We also use the event properties for `onSave` and `onCancel` to let the parent container know what events were trigger in the component and pass back values where appropriate.

```react
return (
  <div>
    <IonPicker
      isOpen={isOpen}
      columns={[DayColumn, SessionTimeColumn]}
      buttons={[
        {
          text: "Cancel",
          role: "cancel",
          handler: value => {
            onCancel()
          }
        },
        {
          text: "Confirm",
          handler: value => {
            onSave(value)
          }
        }
      ]}
    ></IonPicker>
  </div>
);
```

When a user selects the specific items from the picker, below is an example of the object that is return in the `onSave` function. This is the information that will be passed back to the parent component when the function is executed.
```json
{
  "Day" : {
    "text": "Wednesday"
    "value": "Wednesday"
    "columnIndex": 0
  },
  "SessionTime" : {
    "text": "Morning 8a - 12p"
    "value": "Morning"
    "columnIndex": 1
  }
}
```
##Rendering `MyPicker` In App.tsx
We need the appropriate imports in the `App.tsx` file to utilize the `MyPicker` Component and also react state hooks to manage the visibility of the Picker and track the selected values from the picker.
>More information on [Using the State Hook](https://reactjs.org/docs/hooks-state.html)
```javascript
import React, { useState } from "react";
import "./Home.css";
import MyPicker from "../components/MyPicker";
```
We are using typescript in this react example so it is helpful to define the interface for the state information we are tracking for the user selection from `MyPicker` component.
```javascript
export interface ISessionTime {
  weekday: string;
  period: string;
}
```
For managing the visibility of `MyPicker` we are using the `setPickerOpen` function and the state value is stored in `pickerIsOpen`.

For managing the results from the user picker selection, we are using the `setSessionTime` function and state value is stored in `sessionTime`
```javascript
const [pickerIsOpen, setPickerIsOpen] = useState(false);
const [sessionTime, setSessionTime] = useState<ISessionTime | undefined>(
    undefined
  );
```
In the user interface we provide two buttons for interacting with the application state. 
<img src="https://dev-to-uploads.s3.amazonaws.com/i/xpdvstr9cspvbc2e6dhj.png"/>
- "Select Session" : will open the `MyPicker` Component to allow the user to make a selection by setting the `pickerIsOpen` state variable.
- "Clear Session" : Will clear any previously selected values from `sessionTime` state variable
```react
<IonItem>
  <IonButton onClick={() => { setPickerIsOpen(true); }} >
    Select Session
  </IonButton>
  <IonButton onClick={() => { setSessionTime(undefined); }}>
    Clear Session
  </IonButton>
</IonItem>
```
Next we render another `IonItem` wherethe user selection is shown from the state variable `sessionTime` and allow the user to change the selection when the item is clicked by calling `setPickerIsOpen` to update the state and cause the `MyPicker` Component to be rendered.
```react
<IonItem onClick={() => { setPickerIsOpen(true); }} >
  {sessionTime ? (
    <IonLabel>
      {sessionTime?.weekday} - {sessionTime?.period}
    </IonLabel>
  ) : (
    <IonLabel className="placeHolder">Please Select Session</IonLabel>
  )}
</IonItem>
```
Finally we render the actual `MyPicker` Component using the state variables and the appropriate functions passed as properties.

In the `onCancel` event handler, we set state of the `pickerIsOpen` property using `setPickerIsOpen(false)`.

In the `onSave` we need to set the results from `MyPicker` to the local state using `setSessionTime` and we also set the visibility of the picker `setPickerIsOpen(false)`
```react
<MyPicker
  isOpen={pickerIsOpen}
  onCancel={() => {
    setPickerIsOpen(false);
  }}
  onSave={(_value: any) => {
    console.log(_value);
    let { Day, SessionTime } = _value;
    setSessionTime({ weekday: Day.value, period: SessionTime.value });
    setPickerIsOpen(false);
  }}
/>
```
<img src="https://dev-to-uploads.s3.amazonaws.com/i/htyoqxpcs759xnuzfp9j.png" width="400">
### Source Code
{%github aaronksaunders/ionic-react-pickerapp1 %}
--
### About Clearly Innovative
[Clearly Innovative](www.clearlyinnovative.com) is a minority-owned solutions provider that develops digital products. We shape ideas into viable products and transform client needs into enhanced technology solutions. As a leader in early adoption and implementation of cutting edge technologies, Clearly Innovative provides services focused on product strategy, user experience, design and development. According to CEO, Aaron Saunders "We are not just designers and developers, but end-to-end digital solution providers." Clearly Innovative has created a tech education program, Clearly Innovative Education, whose mission is to create a world where people from underrepresented backgrounds can have a seat at the digital table as creators, innovators and entrepreneurs.

### #TheFutureIsWrittenInCode
The Future is Written in Code series, as part of [Inclusive Innovation Incubator](www.in3dc.com), provides introductory and advanced programming classes as well as coding courses with a focus on business and entrepreneurship. Select programming offered includes Coding, UI/UX, Coding & Business, Coding & Entrepreneurship, Business Canvassing, Entrepreneurship: Developing Your Idea into App, to name a few. Please contact info@in3dc.com to find out more!