DEV Community

Cover image for Ionic React Picker Example
Aaron K Saunders for Ionic

Posted on • Updated on

Ionic React Picker Example

Overview

This is a sample Ionic ReactJS Application using the IonPicker Component derived from plain javascript example provided in the Ionic Framework Picker Documentation.

We also use React Hooks to manage the state and the example is based off of the Ionic ReactJS Template so we are supporting Typescript.

Setting Up The Component

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>
}
Enter fullscreen mode Exit fullscreen mode

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


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

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;;
Enter fullscreen mode Exit fullscreen mode
const SessionTimeColumn = {
  name: "SessionTime",
  options: [
    { text: "Morning 8a - 12p", value: "Morning" },
    { text: "Afteroon 1p - 5p", value: "Afteroon" }
  ]
} as PickerColumn;
Enter fullscreen mode Exit fullscreen mode

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.

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

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.

{
  "Day" : {
    "text": "Wednesday"
    "value": "Wednesday"
    "columnIndex": 0
  },
  "SessionTime" : {
    "text": "Morning 8a - 12p"
    "value": "Morning"
    "columnIndex": 1
  }
}
Enter fullscreen mode Exit fullscreen mode

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

import React, { useState } from "react";
import "./Home.css";
import MyPicker from "../components/MyPicker";
Enter fullscreen mode Exit fullscreen mode

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.

export interface ISessionTime {
  weekday: string;
  period: string;
}
Enter fullscreen mode Exit fullscreen mode

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

const [pickerIsOpen, setPickerIsOpen] = useState(false);
const [sessionTime, setSessionTime] = useState<ISessionTime | undefined>(
    undefined
  );
Enter fullscreen mode Exit fullscreen mode

In the user interface we provide two buttons for interacting with the application state.

  • "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
<IonItem>
  <IonButton onClick={() => { setPickerIsOpen(true); }} >
    Select Session
  </IonButton>
  <IonButton onClick={() => { setSessionTime(undefined); }}>
    Clear Session
  </IonButton>
</IonItem>
Enter fullscreen mode Exit fullscreen mode

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.

<IonItem onClick={() => { setPickerIsOpen(true); }} >
  {sessionTime ? (
    <IonLabel>
      {sessionTime?.weekday} - {sessionTime?.period}
    </IonLabel>
  ) : (
    <IonLabel className="placeHolder">Please Select Session</IonLabel>
  )}
</IonItem>
Enter fullscreen mode Exit fullscreen mode

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)

<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);
  }}
/>
Enter fullscreen mode Exit fullscreen mode

Source Code

GitHub logo aaronksaunders / ionic-react-pickerapp1

This is a sample Ionic ReactJS Application using the IonPicker Component derived from plain javascript example provided in the Ionic Framework Picker Documentation.

About Clearly Innovative

Clearly Innovative 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, 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!

Top comments (6)

Collapse
 
patelrikin profile image
Rikin Patel • Edited

Great article, I was actually able to use it in one of my project since there are very few examples available on the internet.
Are you able to expand this article or possibly post another one with expansion of showing pre-selected picker value (default) and then keeping the state of the picker once its closed. I know the component is not destroyed upon close but what if upon certain outside condition you want to reset the state of the picker and pre-select with another value dependent on outside of the component.

Lastly what do you use for Calendar picker? (Not the date time ionic picker)

Collapse
 
aaronksaunders profile image
Aaron K Saunders

Will investigate this weekend

Collapse
 
mrigankpawagi profile image
Mrigank Pawagi

Great article!

Collapse
 
aaronksaunders profile image
Aaron K Saunders

Thanks glad it was helpful

Collapse
 
mohsin708961 profile image
{{7*7}}

Awesome

Collapse
 
aaronksaunders profile image
Aaron K Saunders

thanks