Skip to content
WingoUI
ComponentsTemplatesDocsPricingAI agentsBlogChangelogContact
Components
Buttons & Actions
ButtonButton GroupCopy ButtonDelete ButtonTheme ToggleToggleToggle Group
Inputs
Avatar UploadCalendarCheckboxColor PickerComboboxCountry SelectCron PickerCurrency InputDate PickerDate Range PickerDate Time PickerDuration PickerEmail InputEmoji PickerFile UploadFilter BuilderInputInput GroupListboxMasked InputMention InputMonth PickerMulti SelectNumber InputOTP InputPassword InputPhone InputRadio GroupRatingSearch InputSegmented ControlSelectSignature PadSliderSwitchTag InputTextareaTime PickerTimezone SelectTree Select
Forms
Address InputBooking WidgetCSV ImportFieldForm WizardInline EditInvoice line itemsRich Text EditorSchema Builder
Navigation
Back To TopBounce SidebarBreadcrumbCommand MenuGlobal SearchGooey NavHook SidebarNav MenuNav TabsPaginationProximity SidebarScroll ProgressSidebarStepsTable Of ContentsTabsTopbarUser MenuWorkspace Switcher
Overlays
Alert DialogContext MenuDialogDrawerDropdown MenuFamily DrawerHover CardPopoverShare DialogSheetShortcuts DialogTooltipTour
Feedback
AlertBannerCookie ConsentEmoji ReactionEmpty StateNotification BellNotification CenterProgressRoute ProgressSetup ChecklistSkeletonSpinnerToast
Data Display
Approval FlowAvatarBadgeCalendar ViewCode BlockComment ThreadContact cardCountdownDescription ListDiff ViewerFile ListFile managerFolderGanttJSON ViewerKbdLog ViewerMarkdownPresenceSchedulerTagTimelineTree View
Tables & Lists
Audit LogData TableDeal PipelineEditable GridKanbanListMembers tablePermissions MatrixTableTask ListVirtual List
Charts & Stats
Animated CounterArea chartBar chartDonut chartFunnel chartGaugeGitHub ActivityHeatmap calendarLeaderboardLine chartRadar chartRadial barSparklineStat CardTrackerTrend badge
Layout
AccordionApp ShellCardCollapsibleDetail LayoutEntity HeaderPage HeaderScroll AreaSeparatorSettings LayoutSplit ViewToolbar
Media
Audio PlayerCarouselCSV ViewerDOCX EditorDOCX ViewerExcel ViewerFile SystemImage compareImage CropperImage GalleryImage LightboxLocation MapPDF ViewerPowerPoint ViewerQR CodeStep PlayerVideo Player
AI Kit
Agent Status CardChat MessageChat ThreadChat WidgetConversation ListFluid OrbGrid RevealMatrix OrbModel PickerPrompt InputReasoning IndicatorRule BuilderSuggestion ChipsTool Call TimelineUsage MeterVoice InputWorkflow Canvas
Text & Effects
Background PatternGravity LettersMarqueeTerminalText AnimateText Rotate
Mobile
Action SheetBottom Tab BarFABHaptic ButtonHero HeaderInstall PromptLarge Title HeaderNotification BannerOnboarding CarouselPicker WheelPull To RefreshSlide To ConfirmSticky CTA BarSwipe DeckSwipeable Tabs
Commerce
Cart drawerCategory pickerCheckout stepsCoupon inputFavorite buttonFilter panelListing cardListing gridOrder trackerPricePrice rangePricing tableProduct galleryQuantity stepperReviewsSeller card
Marketing Sections
App Download SectionBlog Cards SectionCTA SectionFAQ SectionFeature GridFeature ShowcaseHero SectionIntegrations SectionLogo CloudMarketing FooterMarketing HeaderMarketing SectionNewsletter SectionPricing SectionStats SectionSteps SectionTeam SectionTestimonials SectionTimeline SectionVideo Section
Blocks
Admin Dashboard PageAdmin ShellAI Chat PageAPI Keys PageAutomation Builder PageCheckout PageCRM Contact PageCRM Pipeline PageError PagesInbox PageInvoice PageKPI DashboardListing Detail PageLogin PageMarketplace Home PageMarketplace Search PageMarketplace ShellMobile App HomeOnboarding FlowOrder History PagePost Listing WizardPricing PageProfile PageRegister PageSettings PageUsers Admin Page
Templates
About PageAcademy PageAccessibility PageAffiliate PageAgency PageAI Product PageAppointment Booking PageBlog PageBlog Post PageBug Bounty PageCareers PageChangelog PageCommunity PageCompare PageContact PageCustomer Story PageCustomers PageDemo Booking PageDevelopers PageDocs Home PageDownload PageEnterprise PageEvents PageExperts PageFAQ PageFeature PageGlossary PageHelp Article PageHelp Center PageHome Services PageImpact PageIntegration Detail PageIntegrations PageJob Detail PageLanding PageLaunch PageLegal PageManifesto PagePortfolio PagePress PageProduct Tour PagePromo PageReal Estate PageReferral PageResearch Report PageRestaurant PageRoadmap PageROI Calculator PageSecurity PageSolutions PageStartups PageStatus PageStorefront PageSwitch PageTemplate Gallery PageTravel PageWaitlist PageYear in Review Page
Hooks & Utilities
AI ChatChart kitCommerceDate utilsFile exportFile typesFiltersForm validationHapticsInvoicingMotion presetsNavigationNumber formatRelative timeRomanian locationsSpreadsheetText matchTonesUIProvideruseClipboarduseConsentuseControllableStateuseCooldownuseDebounceuseKeyboardInsetuseLocaleuseLongPressuseMediaControlsuseMediaQueryuseOverflowItemsusePersistedStateuseScrollEdgesuseScrollStateuseSelectionuseShortcutuseStickToBottom
GalleryTheme

Hooks & Utilities

File types

Hooks & Utilities

File types TypeScript helper for React

File exportFilters
Live props
Options
name
locale
  1. Home
  2. Components
  3. Hooks & Utilities
  4. File types
Pro

File types TypeScript helper for React

v1.0.0·Added in 1.0.0

File type helpers for React that tell what a file is from its name or mime type: kind, icon, tile colors, a type label and a localized size.

Type any file name (or pick a sample) and see the kind, icon tile, type label and size the helpers produce. Switch the locale to compare "2.4 MB" with "2,4 MB".

File types is a Pro React helper in the React hooks and utilities category, written in TypeScript for React 19. It installs as source with npx wingo-ui@latest add file-types, together with Number format and Tones and the npm package lucide-react.

Add to a project

Requirements: React 19, in Next.js (App Router or Pages), Vite or React Router. Installation guide · Next.js setup · Vite setup

npx wingo-ui@latest add file-types

File types is part of Pro, with 298 more Pro items: $8 a month or $150 once. 14-day refund before you download any Pro item. See plans

Usage

Import getFileKind from @/lib/file-types.

import { FILE_KIND_CLASSES, FILE_KIND_ICONS, formatFileSize, getFileKind } from "@/lib/file-types"

export function Attachment({ name, size }: { name: string; size: number }) {
  const kind = getFileKind(name)
  const Icon = FILE_KIND_ICONS[kind]
  return (
    <div className="flex items-center gap-3">
      <span className={`flex size-10 items-center justify-center rounded-[12px] ${FILE_KIND_CLASSES[kind]}`}>
        <Icon className="size-5" />
      </span>
      <span>{name}</span>
      <span>{formatFileSize(size, "en-US")}</span>
    </div>
  )
}

API

  • namedefault ""
    string

    The demo's file name. The extension wins over the mime type because browsers often report none.

  • localedefault "en-US"
    string

    The locale formatFileSize uses in the demo.

  • getFileKind
    (file: { name?: string; type?: string } | string) => FileKind

    The main helper: image, video, audio, pdf, document, spreadsheet, presentation, archive, code, design or other. Reads the extension first (browsers often report no mime type), then the mime type. Accepts a File, an UploadFile, any { name, type } or a plain name or URL.

Parts

  • formatFileSize

    function

    A size in the locale: "2.4 MB" in en-US ("2,4 MB" in de-DE), "320 KB". Binary steps, one decimal below 10 from MB up, and "" for missing or invalid sizes.

    • bytes*
      number | null | undefined

      The size in bytes.

    • locale
      string

      Intl locale for the number; the browser's when left out.

    • returns
      string

      The formatted size, or an empty string.

  • getFileTypeLabel

    function

    A short type badge: "PDF", "XLSX"; the mime subtype when there is no extension; "" when neither says anything.

  • getFileExtension

    function

    The lowercase extension without the dot: "pdf" for "Invoice 2026-0412.PDF". Ignores query strings and returns "" for names like ".env".

  • splitFileName

    function

    Splits "Q3 proposal.pdf" into ["Q3 proposal", ".pdf"], so a long name can truncate in the middle and still show its extension.

  • isPreviewableImage

    function

    Whether a browser can draw the file as an image thumbnail. HEIC and TIFF return false, so they get an icon tile instead.

  • FILE_KIND_ICONS

    constant

    The lucide icon for each kind: FileImage, FileText, FileSpreadsheet, Presentation, FileArchive and the rest.

  • FILE_KIND_CLASSES

    constant

    Tile classes for each kind: red PDF, blue document, green spreadsheet, amber slides and archives, neutral media. The same colors file-upload uses.

  • FILE_KIND_TONES

    constant

    The tone for each kind, for a Badge or any component that takes tone: danger for PDF, info for documents, success for spreadsheets.

  • FILE_KIND_LABELS

    constant

    English names for screen readers and captions ("PDF document", "Spreadsheet"). Pass your own map for other languages.

  • FileKind

    type

    The kind union getFileKind returns.

  • FileLike

    type

    What the helpers accept: a file name or URL, or any { name?, type? } like a File.

Examples

Every kind

The icon tile, label and kind getFileKind gives each family of files.

Thumbnail or icon

isPreviewableImage keeps HEIC and TIFF on an icon tile; the lease has no extension, so its mime type decides.

Long names

splitFileName truncates the base and keeps the extension visible in a narrow column.

Sizes by locale

formatFileSize in binary steps, with one decimal below 10 from MB up.

Dependencies

lucide-reactnumber-formattones

Files

  • lib/file-types.ts

FAQ

Is the File types helper free?

The preview, props and docs are free; copying the source needs a Pro plan. See plans.

How do I install File types?

Run npx wingo-ui@latest add file-types. It also adds the Wingo UI items it builds on (Number format and Tones) and the npm package lucide-react. With shadcn, add the @wingo-ui registry with your API key, then run npx shadcn@latest add @wingo-ui/file-types.

See also

File UploadNumber formatlibToneslib

Used in

Avatar UploadFile managerCSV ImportFile ListFile SystemChat MessagePrompt Input

More React hooks and utilities

FilterslibForm validationlibHapticslibInvoicinglibMotion presetslibNavigationlib
All 36 React hooks and utilities
PreviousFile exportNext Filters

Attachments

  • Invoice 2026-0412.pdfPDF · 242 KB · PDF document
    pdf
  • Contract Northwind Tech LLC.docxDOCX · 1.2 MB · Document
    document
  • Sales report Q3 2026.xlsxXLSX · 2.4 MB · Spreadsheet
    spreadsheet
  • Northwind proposal deck.pptxPPTX · 8 MB · Presentation
    presentation
  • Apartment photos Brooklyn.zipZIP · 46 MB · Archive
    archive
  • IMG_2041.HEICHEIC · 3 MB · Image
    image