A highly customizable React component library for integrating an Unsplash photo picker into your projects.
- 🎨 shadcn/ui compatible — CSS Variables map directly to shadcn design tokens
- 🪶 Lightweight — zero UI framework dependency (no MUI, no Emotion)
- 🧩 Two usage modes — flat props API and compound component API
- 🖼️ Custom renderers — inject
next/image, custom links, custom overlays - 🌑 Dark mode — automatic via
.darkclass ordata-theme="dark" - ♾️ Infinite scroll & button pagination — configurable via
loadMode - 💎 Full TypeScript — complete Unsplash API types exported
- 📦 Dual ESM/CJS — tree-shakable, works in any bundler
- ♿ Accessible — proper ARIA roles, keyboard navigation
npm i react-unsplash
# or
pnpm add react-unsplash
# or
yarn add react-unsplashPeer dependencies: React ≥ 18 and react-dom ≥ 18 are required.
// In your app's root layout or entry file:import'react-unsplash/styles';shadcn/Tailwind users: The styles automatically inherit your CSS variables. No extra config needed.
importReactUnsplashfrom'react-unsplash';importtype{UnsplashPhoto}from'react-unsplash';exportfunctionMyPicker(){const[photos,setPhotos]=useState<UnsplashPhoto[]>([]);const[loading,setLoading]=useState(false);consthandleSearch=async(query: string)=>{setLoading(true);constresults=awaitfetchFromUnsplash(query);// your API callsetPhotos(results);setLoading(false);};return(<ReactUnsplashimages={photos}loading={loading}onSearch={handleSearch}onSelect={(photo)=>console.log('Selected:',photo)}/>);}Note:
react-unsplashis a UI component only — it does not call the Unsplash API. You supply the photos and it handles the display and selection UX. See Setting Up the Unsplash API below.
| Prop | Type | Default | Description |
|---|---|---|---|
images | UnsplashPhoto[] | [] | Array of Unsplash photo objects |
onSelect | (photo: UnsplashPhoto) => void | required | Called when a photo is clicked |
loading | boolean | false | Shows loading indicator |
initValue | string | '' | Initial search value |
onSearch | (value: string) => void | — | Called on every keystroke |
onCommit | (value: string) => void | — | Called when Enter is pressed |
searchPlaceholder | string | 'Search photos...' | Search input placeholder |
maxSearchLength | number | 64 | Max characters in search input |
hasMore | boolean | false | Whether more results are available |
handleLoadMore | () => void | — | Load next page callback |
loadMode | 'scroll' | 'button' | 'scroll' | How to trigger loading more |
displayMode | 'normal' | 'popup' | 'normal' | Inline or modal display |
open | boolean | false | Controls popup visibility |
onClose | () => void | — | Called when popup closes |
cols | number | auto | Number of columns (auto-responsive if omitted) |
gap | number | 8 | Gap between images (px) |
width | number | '100%' | Fixed width of the component |
height | number | 450 | Height of the image grid area |
autoFocus | boolean | true | Auto-focus the search input |
renderImage | (props: ImageRenderProps) => ReactNode | — | Custom image renderer |
renderLink | (props: LinkRenderProps) => ReactNode | — | Custom link renderer |
className | string | — | Extra class on the root element |
classNames | ReactUnsplashClassNames | — | Per-part class name overrides |
style | CSSProperties | — | Inline style / CSS variable overrides |
slots | ReactUnsplashSlots | — | Custom render slot overrides |
<ReactUnsplashclassNames={{root: '',// outermost containersearchWrapper: '',// search bar wrapper divsearchInput: '',// <input> elementloadingBar: '',// loading progress barimageGrid: '',// image grid scroll areaimageItem: '',// each image cardimageOverlay: '',// author overlay on hoverauthorLink: '',// author <a> elementdialog: '',// popup dialog panelloadMore: '',// load more button wrapperemptyState: '',// empty/no-results div}}/><ReactUnsplashslots={{// Custom empty state when no search yetemptyState: <div>Start typing to discover photos!</div>,// Custom empty state for no resultsnoResults: <div>No photos found 😢</div>,// Custom loading spinnerloadingState: <MySpinner/>,// Custom "Load More" button (loadMode="button")loadMoreButton: ({ onClick, loading })=>(<ButtononClick={onClick}disabled={loading}variant="outline">{loading ? <Loader2className="animate-spin"/> : 'Load more'}</Button>),// Custom overlay on top of each imageimageOverlay: (photo)=>(<divclassName="absolute inset-0 flex items-end p-2 bg-gradient-to-t from-black/60"><Badge>{photo.likes} ♥</Badge></div>),// Custom search iconsearchIcon: <MySearchIconclassName="text-primary"/>,}}/>importNextImagefrom'next/image';importNextLinkfrom'next/link';<ReactUnsplashrenderImage={(props)=>(<NextImage{...props}// next/image requires these:unoptimized// or configure remotePatterns for images.unsplash.comclassName="w-full h-auto"/>)}renderLink={(props)=>(<NextLinkhref={props.href}target={props.target}rel={props.rel}>{props.children}</NextLink>)}/>Add to your next.config:
// next.config.mjsconstnextConfig={images: {remotePatterns: [{hostname: 'images.unsplash.com'}],},};For maximum layout control, use the compound components:
import{UnsplashRoot,UnsplashSearch,UnsplashGrid,UnsplashDialog,UnsplashEmptyState,}from'react-unsplash';// ---- Normal layout with custom structure ----<UnsplashRootimages={photos}onSelect={handleSelect}loading={isLoading}hasMore={hasNextPage}handleLoadMore={loadMore}><divclassName="flex flex-col border rounded-xl overflow-hidden"><UnsplashSearchclassName="border-b"/><UnsplashEmptyState><pclassName="text-muted-foreground">Search for beautiful photos...</p></UnsplashEmptyState><UnsplashGridcols={4}height={500}renderImage={(props)=><NextImage{...props}unoptimized/>}/></div></UnsplashRoot>// ---- Popup with compound components ----<UnsplashRootimages={photos}onSelect={handleSelect}onClose={()=>setOpen(false)}><UnsplashDialogopen={isOpen}onClose={()=>setOpen(false)}><UnsplashSearch/><UnsplashGrid/></UnsplashDialog></UnsplashRoot>If your project uses shadcn/ui, react-unsplash automatically inherits your theme colors. No additional configuration needed. The component uses the same CSS variable names (--background, --border, --primary, etc.).
Override any --ru-* variable on the root class or inline:
/* globals.css */
.react-unsplash {
--ru-primary:#6366f1; /* indigo */--ru-radius:0.75rem;
--ru-image-hover:brightness(0.75) saturate(1.2);
}Or per-instance via the style prop:
<ReactUnsplashstyle={{'--ru-primary': '#6366f1','--ru-radius': '1rem',}asReact.CSSProperties}/>Dark mode works automatically with:
- shadcn:
.darkclass on<html>(default shadcn behavior) - Manual:
data-theme="dark"attribute - System:
@media (prefers-color-scheme: dark)← add your own CSS rule if needed
react-unsplash is a pure UI component — you manage the API calls. Here's a recommended setup:
1. Create an API route (keeps your key server-side):
// app/api/unsplash/route.tsexportasyncfunctionGET(request: Request){const{ searchParams }=newURL(request.url);constres=awaitfetch(`https://api.unsplash.com/search/photos?${searchParams}`,{headers: {Authorization: `Client-ID ${process.env.UNSPLASH_ACCESS_KEY}`},});returnResponse.json(awaitres.json());}2. Fetch in your component:
const[photos,setPhotos]=useState([]);consthandleSearch=async(query: string)=>{constres=awaitfetch(`/api/unsplash?query=${query}&per_page=20`);constdata=awaitres.json();setPhotos(data.results);};Get your free API key at unsplash.com/developers.
1. Create your fetch function:
// src/api/unsplash.tsimporttype{UnsplashPhoto}from'react-unsplash';interfaceUnsplashResponse{results: UnsplashPhoto[];total_pages: number;}exportasyncfunctionfetchUnsplashPhotos({
query,
page =1,}: {query: string;page?: number;}): Promise<UnsplashResponse>{if(!query)return{results: [],total_pages: 0};// NOTE: In production, route requests through your own backend to hide your Access Key.constresponse=awaitfetch(`https://api.unsplash.com/search/photos?query=${encodeURIComponent(query)}&page=${page}&per_page=20`,{headers: {Authorization: `Client-ID ${import.meta.env.VITE_UNSPLASH_ACCESS_KEY}`,},});if(!response.ok)thrownewError('Failed to fetch from Unsplash');returnresponse.json();}2. Implement in your component:
importReact,{useState}from'react';import{useInfiniteQuery}from'@tanstack/react-query';importReactUnsplashfrom'react-unsplash';import{fetchUnsplashPhotos}from'./api/unsplash';exportfunctionPhotoPicker(){const[search,setSearch]=useState('');// Set up useInfiniteQuery for pagination/infinite scrollconst{
data,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
isLoading,}=useInfiniteQuery({queryKey: ['unsplashPhotos',search],queryFn: ({ pageParam =1})=>fetchUnsplashPhotos({query: search,page: pageParam}),getNextPageParam: (lastPage,allPages)=>{constnextPage=allPages.length+1;returnnextPage<=lastPage.total_pages ? nextPage : undefined;},initialPageParam: 1,enabled: !!search,});// Flatten infinite query pagesconstphotos=data?.pages.flatMap((page)=>page.results)||[];return(<ReactUnsplashimages={photos}loading={isLoading||isFetchingNextPage}onSearch={(v)=>setSearch(v)}onCommit={(v)=>setSearch(v)}hasMore={hasNextPage}handleLoadMore={fetchNextPage}loadMode="scroll"// use "scroll" for infinite scroll, or "button"onSelect={(photo)=>console.log('Selected:',photo)}/>);}// v1.0 — add this importimport'react-unsplash/styles';// v0.xonSelect={(image: any)=> ...}// v1.0importtype{UnsplashPhoto}from'react-unsplash';onSelect={(photo: UnsplashPhoto)=> ...}// v0.x — required MUI setupimport{ThemeProvider}from'@mui/material';<ThemeProvidertheme={theme}><ReactUnsplash.../></ThemeProvider>
// v1.0 — no wrappers needed
<ReactUnsplash.../>// v0.x — automatically used next/image (broke in non-Next.js apps)// v1.0 — opt-in via renderImage prop<ReactUnsplashrenderImage={(props)=><NextImage{...props}unoptimized/>}/>All existing props (initValue, onSearch, onCommit, hasMore, handleLoadMore, displayMode, open, onClose, cols, gap, width, height) work identically.
MIT © thucne
Made with ❤️ by thucde.dev • Powered by the Unsplash API