CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-gatsby

Blazing fast modern site generator for React with GraphQL data layer and plugin ecosystem

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

components-hooks.mddocs/

Components & Hooks

React components and hooks for building Gatsby applications, including navigation, data fetching, layout components, and client-side utilities.

Capabilities

Link Component

Navigation component that provides client-side routing with prefetching and performance optimizations.

/**
 * Navigation link component with automatic prefetching and performance optimizations
 */
const Link: React.ComponentType<LinkProps>;

interface LinkProps {
  /** The path to navigate to */
  to: string;
  /** Replace current history entry instead of pushing new one */
  replace?: boolean;
  /** Custom state to pass to the location */
  state?: any;
  /** Function to determine if link should be active */
  getProps?: (args: GetPropsArgs) => object;
  /** CSS class name */
  className?: string;
  /** Inline styles */
  style?: React.CSSProperties;
  /** Accessibility attributes */
  activeClassName?: string;
  activeStyle?: React.CSSProperties;
  /** Function called when link is clicked */
  onClick?: (event: React.MouseEvent<HTMLAnchorElement>) => void;
  /** Additional props passed to underlying anchor element */
  [key: string]: any;
}

interface GetPropsArgs {
  isCurrent: boolean;
  isPartiallyCurrent: boolean;
  href: string;
  location: WindowLocation;
}

Usage Examples:

import React from "react";
import { Link } from "gatsby";

// Basic navigation
<Link to="/about">About Us</Link>

// With state and styling
<Link 
  to="/contact" 
  state={{ from: "homepage" }}
  className="nav-link"
  activeClassName="active"
>
  Contact
</Link>

// Dynamic styling based on current location
<Link
  to="/products"
  getProps={({ isCurrent }) => ({
    style: { color: isCurrent ? "red" : "blue" }
  })}
>
  Products
</Link>

useStaticQuery Hook

Hook for executing GraphQL queries in components to fetch data at build time.

/**
 * Hook for executing GraphQL queries in components at build time
 * @param query - Query result from graphql template tag
 * @returns Query result data
 */
function useStaticQuery<TData = any>(query: StaticQueryDocument): TData;

Usage Examples:

import React from "react";
import { useStaticQuery, graphql } from "gatsby";

// Basic site metadata query
const Header = () => {
  const data = useStaticQuery(graphql`
    query HeaderQuery {
      site {
        siteMetadata {
          title
          description
        }
      }
    }
  `);

  return <h1>{data.site.siteMetadata.title}</h1>;
};

// File system query
const ImageGallery = () => {
  const data = useStaticQuery(graphql`
    query ImageQuery {
      allFile(filter: { extension: { regex: "/(jpg|jpeg|png)/" } }) {
        edges {
          node {
            name
            publicURL
          }
        }
      }
    }
  `);

  return (
    <div>
      {data.allFile.edges.map(({ node }) => (
        <img key={node.name} src={node.publicURL} alt={node.name} />
      ))}
    </div>
  );
};

useScrollRestoration Hook

Hook for managing scroll position restoration during navigation.

/**
 * Hook for managing scroll position restoration during navigation
 * @param identifier - Unique identifier for this scroll restoration instance
 * @returns Object with ref and onScroll method for scroll restoration
 */
function useScrollRestoration(identifier: string): {
  ref: React.MutableRefObject<HTMLElement | undefined>;
  onScroll(): void;
};

Usage Examples:

import React from "react";
import { useScrollRestoration } from "gatsby";

const BlogPost = () => {
  // Restore scroll position when navigating back to this page
  useScrollRestoration("blog-post-scroll");

  return (
    <article>
      <h1>Long Blog Post</h1>
      {/* Long content */}
    </article>
  );
};

Script Component

High-performance script loading component with automatic optimization and loading strategies.

/**
 * High-performance script loading component (re-exported from gatsby-script)
 */
const Script: React.ComponentType<ScriptProps>;

interface ScriptProps {
  /** Script source URL */
  src?: string;
  /** Loading strategy */
  strategy?: "post-hydrate" | "idle" | "off-main-thread";
  /** Execute after script loads */
  onLoad?: (event: Event) => void;
  /** Execute if script fails to load */
  onError?: (event: ErrorEvent) => void;
  /** Script ID */
  id?: string;
  /** Additional script attributes */
  [key: string]: any;
}

Usage Examples:

import React from "react";
import { Script } from "gatsby";

const MyPage = () => (
  <div>
    <h1>My Page</h1>
    
    {/* Load analytics after hydration */}
    <Script
      src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"
      strategy="post-hydrate"
      onLoad={() => {
        window.gtag('config', 'GA_MEASUREMENT_ID');
      }}
    />
    
    {/* Load non-critical script when idle */}
    <Script
      src="/scripts/non-critical.js"
      strategy="idle"
    />
    
    {/* Inline script */}
    <Script id="theme-script">
      {`
        const theme = localStorage.getItem('theme') || 'light';
        document.documentElement.setAttribute('data-theme', theme);
      `}
    </Script>
  </div>
);

StaticQuery Component (Deprecated)

Legacy component for static GraphQL queries. Prefer useStaticQuery hook for new development.

/**
 * Legacy component for static GraphQL queries
 * @deprecated Use useStaticQuery hook instead
 */
class StaticQuery<TData = any> extends React.Component<StaticQueryProps<TData>> {}

interface StaticQueryProps<TData = any> {
  query: string;
  render?: (data: TData) => React.ReactNode;
  children?: (data: TData) => React.ReactNode;
}

Slice Component

Component for rendering reusable slices of content that can be shared across pages.

/**
 * Component for rendering reusable slices of content
 */
const Slice: React.ComponentType<SliceProps>;

interface SliceProps {
  /** Unique identifier for the slice */
  alias: string;
  /** Allow fallback content if slice is not found */
  allowEmpty?: boolean;
  /** Additional props passed to the slice component */
  [key: string]: any;
}

Usage Examples:

import React from "react";
import { Slice } from "gatsby";

const Layout = ({ children }) => (
  <div>
    <Slice alias="header" />
    <main>{children}</main>
    <Slice alias="footer" />
  </div>
);

PageRenderer Component

Low-level component for rendering pages with resource loading and error handling.

/**
 * Low-level component for rendering pages with resource loading
 */
class PageRenderer extends React.Component<PageRendererProps> {}

interface PageRendererProps {
  location: WindowLocation;
  pageResources?: PageResources;
  pageContext?: object;
  pageComponentProps?: object;
}

interface PageResources {
  component: React.ComponentType<any>;
  json: PageResourcesJson;
  page: PageResourcesPage;
}

Navigation Functions

Programmatic navigation and path utilities for client-side routing.

/**
 * Navigate programmatically to a new page
 * @param to - Path to navigate to
 * @param options - Navigation options
 * @returns Promise that resolves when navigation completes
 */
function navigate(to: string, options?: NavigateOptions<{}>): Promise<void>;

interface NavigateOptions<State = {}> {
  /** Replace current history entry instead of pushing new one */
  replace?: boolean;
  /** Custom state to pass to the location */
  state?: State;
}

/**
 * Add site path prefix to a path
 * @param path - Path to prefix
 * @returns Prefixed path
 */
function withPrefix(path: string): string;

/**
 * Add asset prefix to a path  
 * @param path - Path to prefix
 * @returns Prefixed path
 */
function withAssetPrefix(path: string): string;

/**
 * Parse URL path into location object
 * @param path - URL path to parse
 * @returns Parsed location object
 */
function parsePath(path: string): WindowLocation;

/**
 * Prefetch resources for a pathname
 * @param pathname - Path to prefetch resources for
 */
function prefetchPathname(pathname: string): void;

Usage Examples:

import { navigate, withPrefix, prefetchPathname } from "gatsby";

// Programmatic navigation
const handleSubmit = async (data) => {
  await saveData(data);
  navigate("/success", { state: { message: "Form submitted!" } });
};

// Using path prefix
const logoUrl = withPrefix("/images/logo.png");

// Prefetch resources on hover
const handleMouseEnter = () => {
  prefetchPathname("/heavy-page");
};

Types

Core Component Types

interface SlicePlaceholderProps {
  alias: string;
  allowEmpty?: boolean;
  [key: string]: any;
}

interface SliceComponentProps<
  DataType = object,
  SliceContextType = object,
  AdditionalSerializableProps = object
> {
  sliceContext: SliceContextType;
  data: DataType;
  [Key in keyof AdditionalSerializableProps]: AdditionalSerializableProps[Key];
}

type WindowLocation<S = unknown> = {
  pathname: string;
  search: string;
  hash: string;
  href: string;
  origin: string;
  protocol: string;
  host: string;
  hostname: string;
  port: string;
  state: S;
  key?: string;
};

docs

browser-apis.md

components-hooks.md

configuration.md

graphql.md

index.md

node-apis.md

ssr-apis.md

tile.json