Ionic React Picker Example

Example code and detailed steps derived on Ionic documentation for using the Picker Control in your solution

Overview

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>
}

What the Picker Will Render

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

Rendering the Picker Component Content

return (
<div>
<IonPicker
isOpen={isOpen}
columns={[DayColumn, SessionTimeColumn]}
buttons={[
{
text: “Cancel”,
role: “cancel”,
handler: value => { onCancel() }
},
{
text: “Confirm”,
handler: value => { onSave(value) }
}
]}>
</IonPicker>
</div>
);
{
“Day” : {
“text”: “Wednesday”
“value”: “Wednesday”
“columnIndex”: 0
},
“SessionTime” : {
“text”: “Morning 8a — 12p”
“value”: “Morning”
“columnIndex”: 1
}
}

Rendering MyPicker In App.tsx

import React, { useState } from “react”;
import “./Home.css”;
import MyPicker from “../components/MyPicker”;
export interface ISessionTime {
weekday: string;
period: string;
}
const [pickerIsOpen, setPickerIsOpen] = useState(false);
const [sessionTime, setSessionTime] = useState<ISessionTime | undefined>(
undefined
);
<IonItem>
<IonButton onClick={() => { setPickerIsOpen(true); }} >
Select Session
</IonButton>
<IonButton onClick={() => { setSessionTime(undefined); }}>
Clear Session
</IonButton>
</IonItem>
<IonItem onClick={() => { setPickerIsOpen(true); }} >
{sessionTime ? (
<IonLabel>
{sessionTime?.weekday} - {sessionTime?.period}
</IonLabel>
) : (
<IonLabel className="placeHolder">Please Select Session</IonLabel>
)}
</IonItem>
<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);
}}
/>

Full Source Code Available:

About Clearly Innovative

#TheFutureIsWrittenInCode

DC based software agency utilizing #Javascript, #Typescript, #HTML5, #Ionicframework, #NodeJS, #Firebase to build web & mobile solutions. https://buff.ly/300Zru

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store