Options
All
  • Public
  • Public/Protected
  • All
Menu

Package graphiql-react

Changelog | API Docs | NPM

@graphiql/react

A React SDK for building integrated GraphQL developer experiences for the web.

Purpose

This package contains a set of building blocks that allow its users to build GraphQL IDEs with ease. It's the set of components that make up GraphiQL, the first and official GraphQL IDE, owned and maintained by the GraphQL Foundation.

There are two kinds of building blocks that this package provides: Stateful context providers for state management and simple UI components.

Getting started

All the state for your GraphQL IDE lives in multiple contexts. The easiest way to get started is by using the GraphiQLProvider component that renders all the individual providers.

There is one required prop called fetcher. This is a function that performs GraphQL request against a given endpoint. You can easily create a fetcher using the method createGraphiQLFetcher from the @graphiql/toolkit package.

import { GraphiQLProvider } from '@graphiql/react';
import { createGraphiQLFetcher } from '@graphiql/toolkit';

const fetcher = createGraphiQLFetcher({
  url: 'https://my.graphql.api/graphql',
});

function MyGraphQLIDE() {
  return (
    <GraphiQLProvider fetcher={fetcher}>
      <div className="graphiql-container">Hello GraphQL</div>
    </GraphiQLProvider>
  );
}

Inside the provider you can now use any UI component provided by @graphiql/react. For example, you can render an operation editor like this:

import { QueryEditor } from '@graphiql/react';

function MyGraphQLIDE() {
  return (
    <GraphiQLProvider fetcher={fetcher}>
      <div className="graphiql-container">
        <QueryEditor />
      </div>
    </GraphiQLProvider>
  );
}

The package also ships the necessary CSS that all its UI components need. You can import them from @graphiql/react/style.css.

Note: In order for these styles to apply, the UI components need to be rendered inside an element that has a class name graphiql-container.

By default, the UI components will try to use the Roboto font for regular text and the Fira Code font for mono-space text. If you want to use the default fonts you can load them using these files:

  • @graphiql/react/font/roboto.css
  • @graphiql/react/font/fira-code.css.

You can, of course, use any other method to load these fonts (for example, loading them from Google Fonts).

Further details on how to use @graphiql/react can be found in the reference implementation of a GraphQL IDE - GraphiQL - in the graphiql package.

Available Stores

GraphiQL uses a set of state management stores, each responsible for a specific part of the IDE's behavior. These stores contain all logic related to state management and can be accessed via custom React hooks.

Core Hooks

  • useStorage: Provides a storage API that can be used to persist state in the browser (by default using localStorage).
  • useTheme: Manages the current theme and provides a method to update it.
  • useMonaco: Access monaco-editor exports and the monaco-graphql instance. Designed for safe use in SSR environments.
  • useGraphiQL: Access the current state.
  • useGraphiQLActions: Trigger actions that mutate the state. This hook never rerenders.

The useGraphiQLActions hook exposes all actions across store slices. The useGraphiQL hook provides access to the following store slices:

Store Slice Responsibilities
editor Manages query, variables, headers, and response editors and tabs
execution Handles the execution of GraphQL requests
plugin Manages plugins and the currently active plugin
schema Fetches, validates, and stores the GraphQL schema

Usage Example

import { useGraphiQL, useGraphiQLActions, useTheme } from '@graphiql/react';

// Get an action to fetch the schema
const { introspect } = useGraphiQLActions();

// Get the current theme and a method to change it
const { theme, setTheme } = useTheme();

// Or use a selector to access specific parts of the state
const schema = useGraphiQL(state => state.schema);
const currentTheme = useTheme(state => state.theme);

All store properties are documented using TSDoc comments. If you're using an IDE like VSCode for development, these descriptions will show up in auto-complete tooltips. All these descriptions can also be found in the API Docs.

Theming

All the components from @graphiql/react have been designed with customization in mind. We achieve this using CSS variables.

All variables that are available for customization can be found in the root.css file.

Colors

Colors are defined using the HSL format. All CSS variables for colors are defined as a list of the three values that make up HSL (hue, saturation and lightness).

This approach allows @graphiql/react to use transparent colors by passing the value of the CSS variable in the hsla function. This enables us to provide truly reusable UI elements where good contrasts are preserved regardless of the elements background.

Development

If you want to develop with @graphiql/react locally - in particular when working on the graphiql package - all you need to do is run yarn dev in the package folder in a separate terminal. This will build the package using Vite. When using it in combination with yarn dev:graphiql (running in the repo root) this will give you auto-reloading when working on graphiql and @graphiql/react simultaneously.

Index

References

Modules

Namespaces

Interfaces

Type aliases

Variables

Functions

Object literals

References

ArgumentIcon

Re-exports ArgumentIcon

Button

Re-exports Button

Button

Re-exports Button

ButtonGroup

Re-exports ButtonGroup

ButtonGroup

Re-exports ButtonGroup

CancellationToken

Re-exports CancellationToken

CancellationTokenSource

Re-exports CancellationTokenSource

ChevronDownIcon

Re-exports ChevronDownIcon

ChevronLeftIcon

Re-exports ChevronLeftIcon

ChevronUpIcon

Re-exports ChevronUpIcon

CloseIcon

Re-exports CloseIcon

CopyIcon

Re-exports CopyIcon

DeprecatedArgumentIcon

Re-exports DeprecatedArgumentIcon

DeprecatedEnumValueIcon

Re-exports DeprecatedEnumValueIcon

DeprecatedFieldIcon

Re-exports DeprecatedFieldIcon

Dialog

Re-exports Dialog

Dialog

Re-exports Dialog

DirectiveIcon

Re-exports DirectiveIcon

DocsFilledIcon

Re-exports DocsFilledIcon

DocsIcon

Re-exports DocsIcon

DropdownMenu

Re-exports DropdownMenu

DropdownMenu

Re-exports DropdownMenu

EditorActions

Re-exports EditorActions

EditorProps

Re-exports EditorProps

EditorProps

Re-exports EditorProps

EditorSlice

Re-exports EditorSlice

Emitter

Re-exports Emitter

EnumValueIcon

Re-exports EnumValueIcon

Environment

Re-exports Environment

ExecuteButton

Re-exports ExecuteButton

ExecuteButton

Re-exports ExecuteButton

ExecutionActions

Re-exports ExecutionActions

ExecutionProps

Re-exports ExecutionProps

ExecutionSlice

Re-exports ExecutionSlice

FieldIcon

Re-exports FieldIcon

GraphiQLPlugin

Re-exports GraphiQLPlugin

GraphiQLProvider

Re-exports GraphiQLProvider

GraphiQLProvider

Re-exports GraphiQLProvider

HeaderEditor

Renames and re-exports RequestHeadersEditor

HeaderEditor

Renames and re-exports RequestHeadersEditor

HistoryIcon

Re-exports HistoryIcon

IDisposable

Re-exports IDisposable

IEvent

Re-exports IEvent

IKeyboardEvent

Re-exports IKeyboardEvent

IMarkdownString

Re-exports IMarkdownString

IMouseEvent

Re-exports IMouseEvent

IPosition

Re-exports IPosition

IRange

Re-exports IRange

IScrollEvent

Re-exports IScrollEvent

ISelection

Re-exports ISelection

ITrustedTypePolicy

Re-exports ITrustedTypePolicy

ITrustedTypePolicyOptions

Re-exports ITrustedTypePolicyOptions

ImagePreview

Re-exports ImagePreview

ImagePreview

Re-exports ImagePreview

ImplementsIcon

Re-exports ImplementsIcon

KEY_MAP

Re-exports KEY_MAP

KeyCode

Re-exports KeyCode

KeyCode

Re-exports KeyCode

KeyCode

Re-exports KeyCode

KeyCode

Re-exports KeyCode

KeyMod

Re-exports KeyMod

KeyMod

Re-exports KeyMod

KeyMod

Re-exports KeyMod

KeyMod

Re-exports KeyMod

KeyboardShortcutIcon

Re-exports KeyboardShortcutIcon

MagnifyingGlassIcon

Re-exports MagnifyingGlassIcon

MarkdownContent

Re-exports MarkdownContent

MarkdownContent

Re-exports MarkdownContent

MarkdownStringTrustedOptions

Re-exports MarkdownStringTrustedOptions

MarkerSeverity

Re-exports MarkerSeverity

MarkerTag

Re-exports MarkerTag

MergeIcon

Re-exports MergeIcon

PenIcon

Re-exports PenIcon

PlayIcon

Re-exports PlayIcon

PluginActions

Re-exports PluginActions

PluginProps

Re-exports PluginProps

PluginSlice

Re-exports PluginSlice

PlusIcon

Re-exports PlusIcon

Position

Re-exports Position

PrettifyIcon

Re-exports PrettifyIcon

QueryEditor

Renames and re-exports OperationEditor

QueryEditor

Renames and re-exports OperationEditor

Range

Re-exports Range

Range

Re-exports Range

Range

Re-exports Range

Range

Re-exports Range

ReloadIcon

Re-exports ReloadIcon

ResponseEditor

Re-exports ResponseEditor

ResponseEditor

Re-exports ResponseEditor

RootTypeIcon

Re-exports RootTypeIcon

SchemaActions

Re-exports SchemaActions

SchemaProps

Re-exports SchemaProps

SchemaReference

Re-exports SchemaReference

SchemaSlice

Re-exports SchemaSlice

Selection

Re-exports Selection

SelectionDirection

Re-exports SelectionDirection

SettingsIcon

Re-exports SettingsIcon

SlicesWithActions

Re-exports SlicesWithActions

Spinner

Re-exports Spinner

Spinner

Re-exports Spinner

StarFilledIcon

Re-exports StarFilledIcon

StarIcon

Re-exports StarIcon

StopIcon

Re-exports StopIcon

Tab

Re-exports Tab

Tab

Re-exports Tab

Tabs

Re-exports Tabs

Tabs

Re-exports Tabs

TabsState

Re-exports TabsState

Theme

Re-exports Theme

Theme

Re-exports Theme

Thenable

Re-exports Thenable

Token

Re-exports Token

ToolbarButton

Re-exports ToolbarButton

ToolbarButton

Re-exports ToolbarButton

ToolbarMenu

Re-exports ToolbarMenu

ToolbarMenu

Re-exports ToolbarMenu

Tooltip

Re-exports Tooltip

Tooltip

Re-exports Tooltip

TrashIcon

Re-exports TrashIcon

TypeIcon

Re-exports TypeIcon

UnStyledButton

Re-exports UnStyledButton

UnStyledButton

Re-exports UnStyledButton

Uri

Re-exports Uri

Uri

Re-exports Uri

Uri

Re-exports Uri

Uri

Re-exports Uri

UriComponents

Re-exports UriComponents

VariableEditor

Renames and re-exports VariablesEditor

VariableEditor

Renames and re-exports VariablesEditor

VisuallyHidden

Re-exports VisuallyHidden

VisuallyHidden

Re-exports VisuallyHidden

Window

Re-exports Window

cleanupDisposables

Re-exports cleanupDisposables

cleanupDisposables

Re-exports cleanupDisposables

cn

Re-exports cn

cn

Re-exports cn

createBoundedUseStore

Re-exports createBoundedUseStore

createBoundedUseStore

Re-exports createBoundedUseStore

createEditor

Re-exports createEditor

createEditor

Re-exports createEditor

createEditorSlice

Re-exports createEditorSlice

createExecutionSlice

Re-exports createExecutionSlice

createPluginSlice

Re-exports createPluginSlice

createSchemaSlice

Re-exports createSchemaSlice

debounce

Re-exports debounce

debounce

Re-exports debounce

editor

Re-exports editor

formatJSONC

Re-exports formatJSONC

formatJSONC

Re-exports formatJSONC

formatShortcutForOS

Re-exports formatShortcutForOS

getOrCreateModel

Re-exports getOrCreateModel

getOrCreateModel

Re-exports getOrCreateModel

isMacOs

Re-exports isMacOs

languages

Re-exports languages

markdown

Re-exports markdown

markdown

Re-exports markdown

monacoStore

Re-exports monacoStore

onEditorContainerKeyDown

Re-exports onEditorContainerKeyDown

onEditorContainerKeyDown

Re-exports onEditorContainerKeyDown

parseJSONC

Re-exports parseJSONC

parseJSONC

Re-exports parseJSONC

pick

Re-exports pick

pick

Re-exports pick

storageStore

Re-exports storageStore

themeStore

Re-exports themeStore

tryParseJSONC

Re-exports tryParseJSONC

tryParseJSONC

Re-exports tryParseJSONC

useChangeHandler

Re-exports useChangeHandler

useChangeHandler

Re-exports useChangeHandler

useCopyQuery

Re-exports useCopyQuery

useDidUpdate

Re-exports useDidUpdate

useDidUpdate

Re-exports useDidUpdate

useDragResize

Re-exports useDragResize

useDragResize

Re-exports useDragResize

useEditorState

Re-exports useEditorState

useEditorState

Re-exports useEditorState

useExecutionContext

Re-exports useExecutionContext

useGraphiQL

Re-exports useGraphiQL

useGraphiQL

Re-exports useGraphiQL

useGraphiQLActions

Re-exports useGraphiQLActions

useGraphiQLActions

Re-exports useGraphiQLActions

useHeadersEditorState

Re-exports useHeadersEditorState

useHeadersEditorState

Re-exports useHeadersEditorState

useMergeQuery

Re-exports useMergeQuery

useMonaco

Re-exports useMonaco

useOperationsEditorState

Re-exports useOperationsEditorState

useOperationsEditorState

Re-exports useOperationsEditorState

useOptimisticState

Re-exports useOptimisticState

useOptimisticState

Re-exports useOptimisticState

usePluginContext

Re-exports usePluginContext

usePrettifyEditors

Re-exports usePrettifyEditors

useSchemaContext

Re-exports useSchemaContext

useStorage

Re-exports useStorage

useStorage

Re-exports useStorage

useStorageContext

Re-exports useStorageContext

useTheme

Re-exports useTheme

useTheme

Re-exports useTheme

useVariablesEditorState

Re-exports useVariablesEditorState

useVariablesEditorState

Re-exports useVariablesEditorState

worker

Re-exports worker

Type aliases

AllActions

AllSlices

EditorProps

EditorProps: ComponentPropsWithoutRef<"div">

MonacoEditor

MonacoEditor: IStandaloneCodeEditor

TabsState

TabsState: { activeTabIndex: number; tabs: TabState[] }

This object describes the state of all tabs.

Type declaration

  • activeTabIndex: number

    The index of the currently active tab with regards to the tabs list of this object.

  • tabs: TabState[]

    A list of state objects for each tab.

Theme

Theme: "light" | "dark" | null

The value null semantically means that the user does not explicitly choose any theme, so we use the system default.

Variables

Const ArgumentIcon

ArgumentIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_ArgumentIcon)

Const Button

Button: ForwardRefExoticComponent<ButtonProps & RefAttributes<HTMLButtonElement>> = forwardRef<HTMLButtonElement, ButtonProps>((props, ref) => (<button{...props}ref={ref}className={cn('graphiql-button',{success: 'graphiql-button-success',error: 'graphiql-button-error',}[props.state!],props.className,)}/>),)

Const ButtonGroup

ButtonGroup: ForwardRefExoticComponent<Omit<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "ref"> & RefAttributes<HTMLDivElement>> = forwardRef<HTMLDivElement,ComponentPropsWithoutRef<'div'>>((props, ref) => (<div{...props}ref={ref}className={cn('graphiql-button-group', props.className)}/>))

Const ChevronDownIcon

ChevronDownIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_ChevronDownIcon)

Const ChevronLeftIcon

ChevronLeftIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_ChevronLeftIcon)

Const ChevronUpIcon

ChevronUpIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_ChevronUpIcon)

Const CloseIcon

CloseIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_CloseIcon)

Const CopyIcon

CopyIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_CopyIcon)

Const DEFAULT_QUERY

DEFAULT_QUERY: string = `# Welcome to GraphiQL## GraphiQL is an in-browser tool for writing, validating, and testing# GraphQL queries.## Type queries into this side of the screen, and you will see intelligent# typeaheads aware of the current GraphQL type schema and live syntax and# validation errors highlighted within the text.## GraphQL queries typically start with a "{" character. Lines that start# with a # are ignored.## An example GraphQL query might look like:## {# field(arg: "value") {# subField# }# }## Keyboard shortcuts:## Prettify query: ${KEY_MAP.prettify.key} (or press the prettify button)## Merge fragments: ${KEY_MAP.mergeFragments.key} (or press the merge button)## Run Query: ${formatShortcutForOS(KEY_MAP.runQuery.key, 'Cmd')} (or press the play button)## Auto Complete: ${KEY_MAP.autoComplete.key} (or just start typing)#`

Const DeprecatedArgumentIcon

DeprecatedArgumentIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_DeprecatedArgumentIcon)

Const DeprecatedEnumValueIcon

DeprecatedEnumValueIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_DeprecatedEnumValueIcon)

Const DeprecatedFieldIcon

DeprecatedFieldIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_DeprecatedFieldIcon)

Const Dialog

Dialog: FC<DialogProps> & { Close: ForwardRefExoticComponent<Omit<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "ref"> & RefAttributes<HTMLButtonElement>>; Description: ForwardRefExoticComponent<DialogDescriptionProps & RefAttributes<HTMLParagraphElement>>; Title: ForwardRefExoticComponent<DialogTitleProps & RefAttributes<HTMLHeadingElement>>; Trigger: ForwardRefExoticComponent<DialogTriggerProps & RefAttributes<HTMLButtonElement>> } = Object.assign(DialogRoot, {Close: DialogClose,Title: D.Title,Trigger: D.Trigger,Description: D.Description,})

Const DirectiveIcon

DirectiveIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_DirectiveIcon)

Const DocsFilledIcon

DocsFilledIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_DocsFilledIcon)

Const DocsIcon

DocsIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_DocsIcon)

Const DropdownMenu

DropdownMenu: FC<DropdownMenuProps> & { Button: ForwardRefExoticComponent<Omit<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "ref"> & RefAttributes<HTMLButtonElement>>; Content: FC<DropdownMenuContentProps>; Item: FC<DropdownMenuItemProps> } = Object.assign(Root, {Button,Item,Content,})

Const EnumValueIcon

EnumValueIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_EnumValueIcon)

Const FieldIcon

FieldIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_FieldIcon)

Const HistoryIcon

HistoryIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_HistoryIcon)

Const ImagePreview

ImagePreview: FC<ImagePreviewProps> & { shouldRender: any } = Object.assign(ImagePreview_, {shouldRender(path: string) {const url = pathToURL(path);return url ? /\.(bmp|gif|jpe?g|png|svg|webp)$/.test(url.pathname) : false;},})

Const ImplementsIcon

ImplementsIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_ImplementsIcon)

Const KEY_BINDINGS

KEY_BINDINGS: { copyQuery: object; mergeFragments: object; prettify: object; runQuery: object } = {prettify: {id: 'graphql-prettify',label: 'Prettify Editors',contextMenuGroupId: 'graphql',keybindings: KEY_MAP.prettify.keybindings,},mergeFragments: {id: 'graphql-merge',label: 'Merge Fragments into Query',contextMenuGroupId: 'graphql',keybindings: KEY_MAP.mergeFragments.keybindings,},runQuery: {id: 'graphql-run',label: 'Run Operation',contextMenuGroupId: 'graphql',keybindings: KEY_MAP.runQuery.keybindings,},copyQuery: {id: 'graphql-copy',label: 'Copy Query',contextMenuGroupId: 'graphql',keybindings: KEY_MAP.copyQuery.keybindings,},} as const

Type declaration

  • copyQuery: object
    • contextMenuGroupId: "graphql"
    • id: "graphql-copy"
    • keybindings: number[]
    • label: "Copy Query"
  • mergeFragments: object
    • contextMenuGroupId: "graphql"
    • id: "graphql-merge"
    • keybindings: number[]
    • label: "Merge Fragments into Query"
  • prettify: object
    • contextMenuGroupId: "graphql"
    • id: "graphql-prettify"
    • keybindings: number[]
    • label: "Prettify Editors"
  • runQuery: object
    • contextMenuGroupId: "graphql"
    • id: "graphql-run"
    • keybindings: number[]
    • label: "Run Operation"

Const KEY_MAP

KEY_MAP: Readonly<{ autoComplete: object; copyQuery: object; mergeFragments: object; prettify: object; refetchSchema: object; runQuery: object; searchInDocs: object; searchInEditor: object }> = Object.freeze({prettify: {key: 'Shift-Ctrl-P',keybindings: [KeyMod.Shift | KeyMod.WinCtrl | KeyCode.KeyP],},mergeFragments: {key: 'Shift-Ctrl-M',keybindings: [KeyMod.Shift | KeyMod.WinCtrl | KeyCode.KeyM],},runQuery: {key: 'Ctrl-Enter',keybindings: [KeyMod.CtrlCmd | KeyCode.Enter],},autoComplete: {key: 'Space',},copyQuery: {key: 'Shift-Ctrl-C',keybindings: [KeyMod.Shift | KeyMod.WinCtrl | KeyCode.KeyC],},refetchSchema: {key: 'Shift-Ctrl-R',},searchInEditor: {key: 'Ctrl-F',},searchInDocs: {key: 'Ctrl-Alt-K',},})

Const KeyboardShortcutIcon

KeyboardShortcutIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_KeyboardShortcutIcon)

Const MONACO_THEME_NAME

MONACO_THEME_NAME: { dark: "graphiql-DARK"; light: "graphiql-LIGHT" } = {dark: 'graphiql-DARK',light: 'graphiql-LIGHT',} as const

Type declaration

  • dark: "graphiql-DARK"
  • light: "graphiql-LIGHT"

Const MagnifyingGlassIcon

MagnifyingGlassIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_MagnifyingGlassIcon)

Const MarkdownContent

MarkdownContent: ForwardRefExoticComponent<MarkdownContentProps & RefAttributes<HTMLDivElement>> = forwardRef<HTMLDivElement, MarkdownContentProps>(({ children, onlyShowFirstChild, type, ...props }, ref) => (<div{...props}ref={ref}className={cn(`graphiql-markdown-${type}`,onlyShowFirstChild && 'graphiql-markdown-preview',props.className,)}dangerouslySetInnerHTML={{ __html: markdown.render(children) }}/>),)

Const MergeIcon

MergeIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_MergeIcon)

Const PenIcon

PenIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_PenIcon)

Const PlayIcon

PlayIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_PlayIcon)

Const PlusIcon

PlusIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_PlusIcon)

Const PrettifyIcon

PrettifyIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_PrettifyIcon)

Const ReloadIcon

ReloadIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_ReloadIcon)

Const RootTypeIcon

RootTypeIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_RootTypeIcon)

Const STORAGE_KEY

STORAGE_KEY: { headers: "headers"; persistHeaders: "shouldPersistHeaders"; query: "query"; tabs: "tabState"; theme: "theme"; variables: "variables"; visiblePlugin: "visiblePlugin" } = {headers: 'headers',visiblePlugin: 'visiblePlugin',query: 'query',variables: 'variables',tabs: 'tabState',persistHeaders: 'shouldPersistHeaders',theme: 'theme',} as const

Type declaration

  • headers: "headers"
  • persistHeaders: "shouldPersistHeaders"
  • query: "query"
  • tabs: "tabState"
  • theme: "theme"
  • variables: "variables"
  • visiblePlugin: "visiblePlugin"

Const SettingsIcon

SettingsIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_SettingsIcon)

Const Spinner

Spinner: ForwardRefExoticComponent<Omit<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "ref"> & RefAttributes<HTMLDivElement>> = forwardRef<HTMLDivElement,ComponentPropsWithoutRef<'div'>>((props, ref) => (<div{...props}ref={ref}className={cn('graphiql-spinner', props.className)}/>))

Const StarFilledIcon

StarFilledIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_StarFilledIcon)

Const StarIcon

StarIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_StarIcon)

Const StopIcon

StopIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_StopIcon)

Const Tab

Tab: ForwardRefExoticComponent<Omit<TabProps, "ref"> & RefAttributes<HTMLLIElement>> & { Button: ForwardRefExoticComponent<Omit<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "ref"> & RefAttributes<HTMLButtonElement>>; Close: ForwardRefExoticComponent<Omit<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "ref"> & RefAttributes<HTMLButtonElement>> } = Object.assign(TabRoot, {Button: TabButton,Close: TabClose,})

Const Tabs

Tabs: ForwardRefExoticComponent<TabsProps & RefAttributes<HTMLUListElement>> = forwardRef<HTMLUListElement, TabsProps>(({ values, onReorder, children, className, ...props }, ref) => (<Reorder.Group{...props}ref={ref}values={values}onReorder={onReorder}axis="x"role="tablist"className={cn('graphiql-tabs', className)}>{children}</Reorder.Group>),)

Const ToolbarButton

ToolbarButton: ForwardRefExoticComponent<ToolbarButtonProps & RefAttributes<HTMLButtonElement>> = forwardRef<HTMLButtonElement, ToolbarButtonProps>(({ label, onClick, ...props }, ref) => {const [error, setError] = useState<Error | null>(null);const handleClick: MouseEventHandler<HTMLButtonElement> = event => {try {// Optional chaining inside try-catch isn't supported yet by react-compilerif (onClick) {onClick(event);}setError(null);} catch (err) {setError(err instanceof Error? err: new Error(`Toolbar button click failed: ${err}`),);}};return (<Tooltip label={label}><UnStyledButton{...props}ref={ref}type="button"className={cn('graphiql-toolbar-button',error && 'error',props.className,)}onClick={handleClick}aria-label={error ? error.message : label}aria-invalid={error ? 'true' : props['aria-invalid']}/></Tooltip>);},)

Const ToolbarMenu

ToolbarMenu: FC<ToolbarMenuProps> & { Item: FC<DropdownMenuItemProps> } = Object.assign(ToolbarMenuRoot, {Item: DropdownMenu.Item,})

Const Tooltip

Tooltip: FC<TooltipContentProps & { label: ReactNode }> & { Provider: FC<TooltipProviderProps> } = Object.assign(TooltipRoot, {Provider: T.Provider,})

Const TrashIcon

TrashIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_TrashIcon)

Const TypeIcon

TypeIcon: FC<SVGProps<SVGSVGElement>> = generateIcon(_TypeIcon)

Const URI_NAME

URI_NAME: { operation: "operation.graphql"; requestHeaders: "request-headers.json"; response: "response.json"; schema: "schema.graphql"; variables: "variables.json" } = {operation: 'operation.graphql',schema: 'schema.graphql',variables: 'variables.json',requestHeaders: 'request-headers.json',response: 'response.json',} as const

Type declaration

  • operation: "operation.graphql"
  • requestHeaders: "request-headers.json"
  • response: "response.json"
  • schema: "schema.graphql"
  • variables: "variables.json"

Const UnStyledButton

UnStyledButton: ForwardRefExoticComponent<Omit<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "ref"> & RefAttributes<HTMLButtonElement>> = forwardRef<HTMLButtonElement,UnStyledButtonProps>((props, ref) => (<button{...props}ref={ref}className={cn('graphiql-un-styled', props.className)}/>))

Const createBoundedUseStore

createBoundedUseStore: <S>(store: S) => { (): ExtractState<S>; <T>(selector: (state: ExtractState<S>) => T): T } = (store => selector => {// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- selector can be `undefined`return useStore(store, selector && useShallow(selector));}) as <S extends StoreApi<unknown>>(store: S,) => {(): ExtractState<S>;<T>(selector: (state: ExtractState<S>) => T): T;}

Type declaration

    • <S>(store: S): { (): ExtractState<S>; <T>(selector: (state: ExtractState<S>) => T): T }
    • Type parameters

      • S: StoreApi<unknown>

      Parameters

      • store: S

      Returns { (): ExtractState<S>; <T>(selector: (state: ExtractState<S>) => T): T }

        • (): ExtractState<S>
        • <T>(selector: (state: ExtractState<S>) => T): T
        • Returns ExtractState<S>

        • Type parameters

          • T

          Parameters

          • selector: (state: ExtractState<S>) => T
              • (state: ExtractState<S>): T
              • Parameters

                • state: ExtractState<S>

                Returns T

          Returns T

Const invalidCharacters

invalidCharacters: string[] = Array.from({ length: 11 }, (_, i) => {// \u2000 -> \u200areturn String.fromCharCode(0x2000 + i);}).concat(['\u2028', '\u2029', '\u202f', '\u00a0'])

Const isMacOs

isMacOs: boolean = typeof navigator !== 'undefined' && navigator.userAgent.includes('Mac')

Const markdown

markdown: MarkdownIt = new MarkdownIt({// we don't want to convert \n to <br> because in Markdown a single newline is not a line break// https://github.com/graphql/graphiql/issues/3155breaks: false,linkify: true,})

Const monacoStore

monacoStore: StoreApi<MonacoStoreType> = createStore<MonacoStoreType>((set, get) => ({actions: {async initialize() {const isInitialized = Boolean(get().monaco);if (isInitialized) {return;}const [monaco, { initializeMode }] = await Promise.all([import('monaco-graphql/esm/monaco-editor.js'),import('monaco-graphql/esm/lite.js'),]);globalThis.__MONACO = monaco;monaco.languages.json.jsonDefaults.setDiagnosticsOptions(JSON_DIAGNOSTIC_OPTIONS,);monaco.editor.defineTheme(MONACO_THEME_NAME.dark, MONACO_THEME_DATA.dark);monaco.editor.defineTheme(MONACO_THEME_NAME.light,MONACO_THEME_DATA.light,);if (navigator.userAgent.includes('Firefox/')) {void patchFirefox();}const monacoGraphQL = initializeMode({diagnosticSettings: MONACO_GRAPHQL_DIAGNOSTIC_SETTINGS,});set({ monaco, monacoGraphQL });},},}))

Dynamically load monaco-editor and monaco-graphql in useEffect after component renders.

Do not convert these to static import statements. In SSR (e.g., Next.js), static imports run on the server where window is undefined and trigger an error.

Const storageStore

storageStore: StoreApi<StorageStoreType> = createStore<StorageStoreType>(() => ({storage: null!,}))

Const themeStore

themeStore: StoreApi<ThemeStoreType> = createStore<ThemeStoreType>(set => ({theme: null,setTheme(theme) {const { storage } = storageStore.getState();storage.set(STORAGE_KEY.theme, theme ?? '');set({ theme });},}))

Const useMonaco

useMonaco: { (): ExtractState<S>; <T>(selector: (state: ExtractState<S>) => T): T } = createBoundedUseStore(monacoStore)

Type declaration

    • (): ExtractState<S>
    • <T>(selector: (state: ExtractState<S>) => T): T
    • Returns ExtractState<S>

    • Type parameters

      • T

      Parameters

      • selector: (state: ExtractState<S>) => T
          • (state: ExtractState<S>): T
          • Parameters

            • state: ExtractState<S>

            Returns T

      Returns T

Const useStorageContext

useStorageContext: useStorage = useStorage
deprecated

Use const storage = useStorage() instead.

Const useTheme

useTheme: { (): ExtractState<S>; <T>(selector: (state: ExtractState<S>) => T): T } = createBoundedUseStore(themeStore)

Type declaration

    • (): ExtractState<S>
    • <T>(selector: (state: ExtractState<S>) => T): T
    • Returns ExtractState<S>

    • Type parameters

      • T

      Parameters

      • selector: (state: ExtractState<S>) => T
          • (state: ExtractState<S>): T
          • Parameters

            • state: ExtractState<S>

            Returns T

      Returns T

Functions

Const DEFAULT_PRETTIFY_QUERY

  • DEFAULT_PRETTIFY_QUERY(query: string): Promise<string>

Const ExecuteButton

  • ExecuteButton(): Element

Const GraphiQLProvider

  • GraphiQLProvider(__namedParameters: { defaultTheme: undefined | null | "light" | "dark"; editorTheme: undefined | { dark: MonacoTheme; light: MonacoTheme }; props: props; storage: undefined | Storage }): Element
  • Parameters

    • __namedParameters: { defaultTheme: undefined | null | "light" | "dark"; editorTheme: undefined | { dark: MonacoTheme; light: MonacoTheme }; props: props; storage: undefined | Storage }
      • defaultTheme: undefined | null | "light" | "dark"
      • editorTheme: undefined | { dark: MonacoTheme; light: MonacoTheme }
      • props: props
      • storage: undefined | Storage

    Returns Element

Const OperationEditor

  • OperationEditor(__namedParameters: { onClickReference: undefined | onClickReference; onEdit: undefined | onEdit; props: props }): Element

Const RequestHeadersEditor

  • RequestHeadersEditor(__namedParameters: { onEdit: undefined | onEdit; props: props }): Element

Const ResponseEditor

  • ResponseEditor(__namedParameters: { ResponseTooltip: undefined | ComponentClass<{ position: Position; word: IWordAtPosition }, any> | FunctionComponent<{ position: Position; word: IWordAtPosition }>; props: props }): Element
  • Parameters

    • __namedParameters: { ResponseTooltip: undefined | ComponentClass<{ position: Position; word: IWordAtPosition }, any> | FunctionComponent<{ position: Position; word: IWordAtPosition }>; props: props }
      • ResponseTooltip: undefined | ComponentClass<{ position: Position; word: IWordAtPosition }, any> | FunctionComponent<{ position: Position; word: IWordAtPosition }>
      • props: props

    Returns Element

Const StorageStore

  • StorageStore(__namedParameters: { children: ReactNode; storage: undefined | Storage }): null | ReactElement<unknown, string | ((props: P) => ReactElement<any, any> | null) | {}>

Const ThemeStore

  • ThemeStore(__namedParameters: { children: ReactNode; defaultTheme: Theme; editorTheme: { dark: "graphiql-DARK"; light: "graphiql-LIGHT" } | { dark: MonacoTheme; light: MonacoTheme } }): ReactElement<unknown, string | ((props: P) => ReactElement<any, any> | null) | {}>
  • Parameters

    • __namedParameters: { children: ReactNode; defaultTheme: Theme; editorTheme: { dark: "graphiql-DARK"; light: "graphiql-LIGHT" } | { dark: MonacoTheme; light: MonacoTheme } }
      • children: ReactNode
      • defaultTheme: Theme
      • editorTheme: { dark: "graphiql-DARK"; light: "graphiql-LIGHT" } | { dark: MonacoTheme; light: MonacoTheme }

    Returns ReactElement<unknown, string | ((props: P) => ReactElement<any, any> | null) | {}>

Const TooltipRoot

  • TooltipRoot(__namedParameters: { align: "center" | "start" | "end"; children: ReactNode; label: ReactNode; side: "top" | "right" | "bottom" | "left"; sideOffset: number }): Element
  • Parameters

    • __namedParameters: { align: "center" | "start" | "end"; children: ReactNode; label: ReactNode; side: "top" | "right" | "bottom" | "left"; sideOffset: number }
      • align: "center" | "start" | "end"
      • children: ReactNode
      • label: ReactNode
      • side: "top" | "right" | "bottom" | "left"
      • sideOffset: number

    Returns Element

Const VariablesEditor

  • VariablesEditor(__namedParameters: { onEdit: undefined | onEdit; props: props }): Element

cleanupDisposables

clearHeadersFromTabs

createEditor

  • createEditor(domElement: RefObject<HTMLDivElement>, options: IStandaloneEditorConstructionOptions): MonacoEditor

Const createEditorSlice

  • createEditorSlice(initial: Pick<EditorSlice, "onTabChange" | "onEditOperationName" | "defaultHeaders" | "defaultQuery" | "onCopyQuery" | "onPrettifyQuery" | "initialQuery" | "initialVariables" | "initialHeaders" | "externalFragments" | "shouldPersistHeaders" | "tabs" | "activeTabIndex" | "uriInstanceId">): (Anonymous function)
  • Parameters

    • initial: Pick<EditorSlice, "onTabChange" | "onEditOperationName" | "defaultHeaders" | "defaultQuery" | "onCopyQuery" | "onPrettifyQuery" | "initialQuery" | "initialVariables" | "initialHeaders" | "externalFragments" | "shouldPersistHeaders" | "tabs" | "activeTabIndex" | "uriInstanceId">

    Returns (Anonymous function)

Const createExecutionSlice

  • createExecutionSlice(initial: Pick<ExecutionSlice, "getDefaultFieldNames" | "fetcher" | "overrideOperationName">): (Anonymous function)

Const createPluginSlice

  • createPluginSlice(initial: Pick<PluginSlice, "referencePlugin" | "onTogglePluginVisibility">): (Anonymous function)

Const createSchemaSlice

  • createSchemaSlice(initial: Pick<SchemaSlice, "onSchemaChange" | "inputValueDeprecation" | "introspectionQueryName" | "schemaDescription">): (Anonymous function)

createTab

  • createTab(__namedParameters?: { headers: null | string; query: null | string; variables: null | string }): TabState

debounce

  • debounce<F>(duration: number, fn: F): debounce

formatJSONC

  • formatJSONC(content: string): Promise<string>

formatShortcutForOS

fuzzyExtractOperationName

  • fuzzyExtractOperationName(str: string): string | null

getDefaultTabState

  • getDefaultTabState(__namedParameters: { defaultHeaders: undefined | string; defaultQuery: string; defaultTabs: TabDefinition[]; headers: null | string; query: null | string; shouldPersistHeaders: undefined | false | true; variables: null | string }): getDefaultTabState
  • Parameters

    • __namedParameters: { defaultHeaders: undefined | string; defaultQuery: string; defaultTabs: TabDefinition[]; headers: null | string; query: null | string; shouldPersistHeaders: undefined | false | true; variables: null | string }
      • defaultHeaders: undefined | string
      • defaultQuery: string
      • defaultTabs: TabDefinition[]
      • headers: null | string
      • query: null | string
      • shouldPersistHeaders: undefined | false | true
      • variables: null | string

    Returns getDefaultTabState

getOrCreateModel

  • getOrCreateModel(__namedParameters: { $uri: string; value: string }): getOrCreateModel

normalizeWhitespace

Const onEditorContainerKeyDown

  • onEditorContainerKeyDown(event: KeyboardEvent<HTMLDivElement>): void

parseJSONC

pick

  • pick<T, K>(...keys: K[]): pick

serializeTabState

setPropertiesInActiveTab

tryParseJSONC

useChangeHandler

  • useChangeHandler(callback: ((value: string) => void) | undefined, storageKey: string | null, tabProperty: "variables" | "headers"): useChangeHandler

useCopyQuery

Const useDidUpdate

  • useDidUpdate(fn: EffectCallback, dependencies: undefined | DependencyList): void

useDragResize

  • useDragResize(__namedParameters: { defaultSizeRelation: number; direction: "horizontal" | "vertical"; initiallyHidden: undefined | "first" | "second"; onHiddenElementChange: undefined | onHiddenElementChange; sizeThresholdFirst: number; sizeThresholdSecond: number; storageKey: undefined | string }): useDragResize
  • Parameters

    • __namedParameters: { defaultSizeRelation: number; direction: "horizontal" | "vertical"; initiallyHidden: undefined | "first" | "second"; onHiddenElementChange: undefined | onHiddenElementChange; sizeThresholdFirst: number; sizeThresholdSecond: number; storageKey: undefined | string }
      • defaultSizeRelation: number
      • direction: "horizontal" | "vertical"
      • initiallyHidden: undefined | "first" | "second"
      • onHiddenElementChange: undefined | onHiddenElementChange
      • sizeThresholdFirst: number
      • sizeThresholdSecond: number
      • storageKey: undefined | string

    Returns useDragResize

Const useEditorState

  • useEditorState(editor: "query" | "variable" | "header"): [string, (val: string) => void]

useExecutionContext

useGraphiQL

Const useGraphiQLActions

Const useHeadersEditorState

  • useHeadersEditorState(): [headers: string, setHeaders: (content: string) => void]

useMergeQuery

Const useOperationsEditorState

  • useOperationsEditorState(): [operations: string, setOperations: (content: string) => void]

useOptimisticState

  • useOptimisticState(__namedParameters: [string, (val: string) => void]): ReturnType<typeof useEditorState>
  • Implements an optimistic caching strategy around a useState-like hook in order to prevent loss of updates when the hook has an internal delay and the update function is called again before the updated state is sent out.

    Use this as a wrapper around useOperationsEditorState, useVariablesEditorState, or useHeadersEditorState if you anticipate calling them with great frequency (due to, for instance, mouse, keyboard, or network events).

    example
    const [operationsString, handleEditOperations] =
      useOptimisticState(useOperationsEditorState());

    Parameters

    • __namedParameters: [string, (val: string) => void]

    Returns ReturnType<typeof useEditorState>

usePluginContext

usePrettifyEditors

useSchemaContext

Const useStorage

  • useStorage(): StorageAPI

Const useVariablesEditorState

  • useVariablesEditorState(): [variables: string, setVariables: (content: string) => void]

Object literals

Const JSON_DIAGNOSTIC_OPTIONS

JSON_DIAGNOSTIC_OPTIONS: object

allowComments

allowComments: true = true

trailingCommas

trailingCommas: "ignore" = "ignore"

Const MONACO_GRAPHQL_DIAGNOSTIC_SETTINGS

MONACO_GRAPHQL_DIAGNOSTIC_SETTINGS: object

validateVariablesJSON

validateVariablesJSON: {}

Type declaration

jsonDiagnosticSettings

jsonDiagnosticSettings: object

schemaValidation

schemaValidation: "error" = "error"

validate

validate: true = true

Const MONACO_THEME_DATA

MONACO_THEME_DATA: object

dark

dark: object

base

base: "vs-dark" = "vs-dark"

colors

colors: IColors = getBaseColors('dark')

inherit

inherit: true = true

rules

rules: { foreground: string; token: string }[] = [{token: 'argument.identifier.gql',foreground: '#908aff',},]

light

light: object

base

base: "vs" = "vs"

colors

colors: IColors = getBaseColors('light')

inherit

inherit: true = true

rules

rules: { foreground: string; token: string }[] = [{token: 'argument.identifier.gql',foreground: '#6c69ce',},]

Generated using TypeDoc