The Google Drive Picker web component offers a seamless way to integrate the Google Picker API into your web applications. This component is framework-agnostic, meaning it works effortlessly with React, Svelte, Vue, Angular, and more.
The Google Picker API is a JavaScript API that allows users to select or upload Google Drive files. This component acts as a "File Open" dialog, providing access to and interaction with files stored on Google Drive.
Explore the storybook demo to see the component in action.
See the framework specific demos:
Install using NPM or similar.
npm i @googleworkspace/drive-picker-elementA CDN version is also available. See the unpkg.
<script src="https://unpkg.com/@googleworkspace/drive-picker-element/dist/index.iife.min.js"></script>To use the drive-picker component in your project, follow these steps:
First, import the drive-picker component in your JavaScript file:
import "@googleworkspace/drive-picker-element";This isn't necessary if you're using the CDN version.
Next, add the drive-picker component to your HTML file. Replace YOUR_CLIENT_ID and YOUR_APP_ID with your actual client ID and app ID.
Note: You can find these values in the Google Cloud Console under "APIs & Services" > "Credentials". You can also follow this guide to create a new OAuth 2.0 client ID.
<drive-picker client-id="YOUR_CLIENT_ID" app-id="YOUR_APP_ID">
<drive-picker-docs-view starred="true"></drive-picker-docs-view>
</drive-picker>Note: If you wish to register the component with a different name, you can import the components individually and call
customElements.define()manually:
import {
DrivePickerElement,
DrivePickerDocsViewElement,
} from "@googleworkspace/drive-picker-element/drive-picker";
customElements.define("custom-drive-picker", DrivePickerElement);
customElements.define(
"custom-drive-picker-docs-view",
DrivePickerDocsViewElement,
);If you already have an OAuth token, you can pass it to the drive-picker component using the oauth-token attribute. This will authenticate the user without requiring them to sign in again.
<drive-picker app-id="YOUR_APP_ID" oauth-token="OAUTH_TOKEN"></drive-picker>If you don't have an OAuth token, you can listen for the "picker-oauth-response" event to get the token after the user has authenticated. This library wraps the Google Identity Services library to make it easier to authenticate users.
The drive-picker component emits several events that you can listen to. Here is an example of how to listen to these events:
<drive-picker client-id="YOUR_CLIENT_ID" app-id="YOUR_APP_ID">
<drive-picker-docs-view starred="true"></drive-picker-docs-view>
</drive-picker>
<script>
const element = document.querySelector("drive-picker");
element.addEventListener("picker-oauth-response", console.log);
element.addEventListener("picker-oauth-error", console.log);
element.addEventListener("picker-picked", console.log);
element.addEventListener("picker-canceled", console.log);
</script>Most of these events return the Picker ResponseObject as the event detail. For example, the "picker-picked" CustomEvent contains details about the selected files:
{
"type": "picker-picked",
"detail": {
"action": "picked",
"docs": [
{
"id": "OMITTED",
"mimeType": "application/pdf",
"name": "OMITTED",
"url": "https://drive.google.com/file/d/OMITTED/view?usp=drive_web",
"sizeBytes": 12345
// ... other properties omitted
}
]
}
}The "picker-oauth-response" event returns the OAuth token response as the event detail:
{
"type": "picker-oauth-response",
"detail": {
"access_token": "OMITTED",
"expires_in": 3599,
"scope": "https://www.googleapis.com/auth/drive.file",
"token_type": "Bearer"
}
}To make the picker visible, set the visible property of the drive-picker element to true:
<drive-picker client-id="YOUR_CLIENT_ID" app-id="YOUR_APP_ID"></drive-picker>
<script>
const element = document.querySelector("drive-picker");
element.visible = true;
</script>After the picker dialog has been closed, the visible property will be reset to false.
To use the component in a React application, you can extend the global JSX namespace as follows:
import type {
DrivePickerElement,
DrivePickerDocsViewElement,
DrivePickerElementProps,
DrivePickerDocsViewElementProps,
} from "@googleworkspace/drive-picker-element";
declare global {
namespace React.JSX {
interface IntrinsicElements {
"drive-picker": React.DetailedHTMLProps<
React.HTMLAttributes<DrivePickerElement> & DrivePickerElementProps,
DrivePickerElement
>;
"drive-picker-docs-view": React.DetailedHTMLProps<
React.HTMLAttributes<DrivePickerDocsViewElement> &
DrivePickerDocsViewElementProps,
DrivePickerDocsViewElement
>;
}
}
}The above snippet can be added to a declaration file (e.g. app.d.ts) in your React project.
When working with React or Next.js, you need to use useEffect and useRef to properly attach event listeners to the web component. Here's a complete example:
import { useEffect, useRef, useState } from "react";
import type {
DrivePickerElement,
PickerPickedEvent,
} from "@googleworkspace/drive-picker-element";
export default function DrivePicker() {
const pickerRef = useRef<DrivePickerElement>(null);
const [selectedFiles, setSelectedFiles] = useState<any[]>([]);
useEffect(() => {
// Dynamically import the web component
import("@googleworkspace/drive-picker-element");
}, []);
useEffect(() => {
const pickerElement = pickerRef.current;
if (!pickerElement) return;
// Use the non-deprecated event names (with hyphens, not colons)
const handlePicked = (e: Event) => {
const event = e as PickerPickedEvent;
console.log("Files picked:", event.detail);
setSelectedFiles(event.detail.docs || []);
};
const handleCanceled = (e: Event) => {
console.log("Picker canceled");
};
const handleOAuthError = (e: Event) => {
console.error("OAuth error:", e);
};
// Add event listeners
pickerElement.addEventListener("picker-picked", handlePicked);
pickerElement.addEventListener("picker-canceled", handleCanceled);
pickerElement.addEventListener("picker-oauth-error", handleOAuthError);
// Cleanup function to remove event listeners
return () => {
pickerElement.removeEventListener("picker-picked", handlePicked);
pickerElement.removeEventListener("picker-canceled", handleCanceled);
pickerElement.removeEventListener("picker-oauth-error", handleOAuthError);
};
}, []);
return (
<div>
<drive-picker
ref={pickerRef}
client-id="YOUR_CLIENT_ID"
app-id="YOUR_APP_ID"
>
<drive-picker-docs-view></drive-picker-docs-view>
</drive-picker>
{selectedFiles.length > 0 && (
<div>
<h3>Selected Files:</h3>
<ul>
{selectedFiles.map((file) => (
<li key={file.id}>{file.name}</li>
))}
</ul>
</div>
)}
</div>
);
}Important notes for React/Next.js:
-
Dynamic import: In Next.js, import the component dynamically inside
useEffectto avoid server-side rendering issues, since web components need to run in the browser. -
Proper cleanup: Always remove event listeners in the cleanup function to prevent memory leaks.
-
Wait for the element: Make sure the ref is populated before adding event listeners.
To report issues or feature requests for the underlying Drive Picker, please use the Google Picker issue tracker. For all other issues, please use the GitHub issue tracker.
The drive-picker web component provides a convenient way to declaratively
build
google.picker.Picker
by using the component attributes mapped to the corresponding methods of
google.picker.PickerBuilder.
| Name | Type | Description |
|---|---|---|
app-id |
string |
The Google Drive app ID. See PickerBuilder.setAppId. |
client-id |
string |
The OAuth 2.0 client ID. See Using OAuth 2.0 to Access Google APIs. |
debounce-delay |
number |
The debounce delay in milliseconds before building the picker after an attribute change. |
developer-key |
string |
The API key for accessing Google Picker API. See PickerBuilder.setDeveloperKey. |
hide-title-bar |
"default"|"true"|"false" |
Hides the title bar of the picker if set to true. See PickerBuilder.hideTitleBar. |
locale |
string |
The locale to use for the picker. See PickerBuilder.setLocale. |
max-items |
number |
The maximum number of items that can be selected. See PickerBuilder.setMaxItems. |
mine-only |
boolean |
If set to true, only shows files owned by the user. See PickerBuilder.enableFeature. |
multiselect |
boolean |
Enables multiple file selection if set to true. See PickerBuilder.enableFeature. |
nav-hidden |
boolean |
Hides the navigation pane if set to true. See PickerBuilder.enableFeature. |
oauth-token |
string |
The OAuth 2.0 token for authentication. See PickerBuilder.setOAuthToken. |
origin |
string |
The origin parameter for the picker. See PickerBuilder.setOrigin. |
relay-url |
string |
The relay URL for the picker. See PickerBuilder.setRelayUrl. |
scope |
string |
The OAuth 2.0 scope for the picker. The default is https://www.googleapis.com/auth/drive.file. See Drive API scopes. |
title |
string |
The title of the picker. See PickerBuilder.setTitle. |
hd |
string |
The hosted domain to restrict sign-in to. (Optional) See the hd field in the OpenID Connect docs. |
include-granted-scopes |
boolean |
Enables applications to use incremental authorization. See TokenClientConfig.include_granted_scopes. |
login-hint |
string |
An email address or an ID token 'sub' value. Google will use the value as a hint of which user to sign in. See the login_hint field in the OpenID Connect docs. |
prompt |
""|"none"|"consent"|"select_account" |
A space-delimited, case-sensitive list of prompts to present the user. See TokenClientConfig.prompt |
| Name | Type | Description |
|---|---|---|
picker-oauth-error |
OAuthErrorEvent |
Triggered when an error occurs in the OAuth flow. See the error guide. Note that the TokenResponse object can have error fields. |
picker-oauth-response |
OAuthResponseEvent |
Triggered when an OAuth flow completes. See the token model guide. |
picker-canceled |
PickerCanceledEvent |
Triggered when the user cancels the picker dialog. See ResponseObject. |
picker-picked |
PickerPickedEvent |
Triggered when the user picks one or more items. See ResponseObject. |
picker-error |
PickerErrorEvent |
Triggered when an error occurs. See ResponseObject. |
| Name | Description |
|---|---|
| default | The default slot contains View elements to display in the picker. Each View element should implement a property view of type google.picker.View. |
| Name | Type | Description |
|---|---|---|
visible |
boolean |
Controls the visibility of the picker after the picker dialog has been closed. If any of the attributes change, the picker will be rebuilt and the visibility will be reset. |
tokenClientConfig |
`Omit< |
google.accounts.oauth2.TokenClientConfig,
"callback" \| "error_callback" >` | |
The drive-picker-docs-view element is used to define a google.picker.DocsView.
| Name | Type | Description |
|---|---|---|
enable-drives |
"default"|"true"|"false" |
Whether to allow the user to select files from shared drives. See DocsView.enableDrives. |
file-ids |
string |
A comma-separated list of file IDs to filter the view. See View.setFileIds. |
include-folders |
"default"|"true"|"false" |
Whether to include folders in the view. See DocsView.includeFolders. |
mime-types |
string |
A comma-separated list of MIME types to filter the view. See View.setMimeTypes. |
mode |
string |
The mode of the view. See DocsViewMode. |
owned-by-me |
"default"|"true"|"false" |
Whether to show files owned by the user. See DocsView.ownedByMe. |
parent |
string |
The ID of the folder to view. See DocsView.setParent. |
query |
string |
The query string to filter the view. See View.setQuery. |
select-folder-enabled |
"default"|"true"|"false" |
Whether to allow the user to select folders. See DocsView.selectFolderEnabled. |
starred |
"default"|"true"|"false" |
Whether to show starred files. See DocsView.starred. |
view-id |
string |
The keyof typeof google.picker.ViewId. For example, "DOCS", which is equivalent to google.picker.ViewId.DOCS. See ViewId. |
| Name | Type | Description |
|---|---|---|
view |
google.picker.DocsView |
Gets the Google Drive Picker view based on the current attribute values. |
