React Haiku

repository·main·Indexed 21 days ago

https://github.com/davidhdev/haiku

A lightweight React Hook and Utility library (version 2.4.1) designed to speed up development. It provides a collection of specialized hooks for DOM interaction, browser APIs, and state management—including useHover, useClickOutside, useClipboard, and useCookie—alongside utility components like For for dynamic list rendering. Requires React version 16.8.0 or higher.

Tokens
31.8K
Snippets
98
Records
135
Agent score
76%

What's inside react-haiku

  1. Use the Classes component for conditional styling

    main

    The Classes component is a utility that conditionally applies CSS classes based on multiple independent boolean conditions. It allows you to manage complex class toggling by passing an object where keys are class names and values are the boolean conditions that determine if those classes should be applied.

    import React, { useState } from 'react';
    import { Classes } from 'react-haiku';
    
    const Component = () => {
      const [hasError, setHasError] = useState(false);
      const [isSquared, setIsSquared] = useState(false);
      const [isDisabled, setIsDisabled] = useState(false);
    
      return (
        <Classes
          as="input"
          className="demo-classes-input"
          toggleClasses={{
            'demo-classes-input--error': hasError,
            'demo-classes-input--squared': isSquared,
            'demo-classes-input--disabled': isDisabled,
          }}
        />
      );
    };
    
    export default Component;
  2. Use the Class component for conditional styling

    main

    The Class component is a utility component that conditionally applies a CSS class to an element based on a boolean condition. It is useful for toggling styles dynamically without manually managing string concatenations for class names.

    To use it, import Class from react-haiku and provide a condition prop. When condition is true, the toggleClass is added to the element alongside the base className.

    import React, { useState } from 'react';
    import { Class } from 'react-haiku';
    
    const Component = () => {
      const [isActive, setIsActive] = useState(false);
      
      const toggleActive = () => {
        setIsActive(!isActive);
      };
    
      return (
        <div>
          <button onClick={toggleActive}>
            {isActive ? 'Deactivate' : 'Activate'}
          </button>
    
          <Class
            className="box"
            condition={isActive}
            toggleClass="active"
            as="section"
          >
            This is a box that will toggle its class based on the button click.
          </Class>
        </div>
      );
    };
    
    export default Component;
  3. Configure Haiku for Next.js

    main

    Because Haiku uses ES6 modules, older Next.js projects (prior to Next 14) may not transpile it automatically as an external dependency.

    Note: These steps should no longer be required in Next 14+ projects.

    To set up compatibility in older versions:

    1. Install next-transpile-modules.
    2. Wrap your next.config.js with withTM and include 'react-haiku' in the transpilation list.
    npm install next-transpile-modules
    const withTM = require('next-transpile-modules')(['react-haiku']);
    module.exports = withTM({});
  4. Use the Show component for conditional rendering

    main

    The Show component provides a way to perform complex conditional rendering in React. It works by wrapping multiple Show.When components and an optional Show.Else component.

    • Use Show.When to render content when a specific condition is met via the isTrue prop. You can use multiple When components.
    • Use Show.Else to render fallback content when none of the When conditions are truthy. Else can only be used once within a Show block.
    import { useState } from 'react';
    import { Show } from 'react-haiku';
    
    export const Component = () => {
        const [number, setNumber] = useState(6);
    
        return (
            <Show>
                <Show.When isTrue={number === 6}>
                    <b>Number is 6!</b>
                    <button onClick={() => setNumber(number + 1)}>Increment</button>
                </Show.When>
    
                <Show.When isTrue={number === 7}>
                    <b>Number is 7!</b>
                    <button onClick={() => setNumber(number + 1)}>Increment</button>
                </Show.When>
    
                <Show.Else>
                    <b>No valid number found!</b>
                    <button onClick={() => setNumber(6)}>Reset</button>
                </Show.Else>
            </Show>
        );
    }
  5. Configure useIdle with custom events and initial state

    main

    You can customize the behavior of useIdle by passing an options object as the second argument.

    Custom Options

    • events: A string array of event names that trigger activity. If not provided, it defaults to ['keypress', 'mousemove', 'touchmove', 'click', 'scroll'].
    • initialState: A boolean representing the starting activity state.
    import { useIdle } from "react-haiku"
    
    export const Component = () => {
        // Only responds to 'click' and 'touchstart' events
        // Starts in an 'Active' state (false)
        const idle = useIdle(1000, { 
            events: ['click', 'touchstart'], 
            initialState: false 
        });
    
        return (
            <>
                <b>Works only with click/touch events!</b>
                <b>Current Status: {idle ? 'Idle' : 'Active'}</b>
            </>
        );
    }
    import { useIdle } from "react-haiku"
    
    export const Component = () => {
        const idle = useIdle(1000, { events: ['click', 'touchstart'], initialState: false });
    
        return (
            <>
                <b>Works only with click/touch events!</b>
                <b>Current Status: {idle ? 'Idle' : 'Active'}</b>
            </>
        );
    }
  6. Use the RenderAfter component to delay rendering

    main

    The RenderAfter component allows you to wrap components or JSX code and delay their appearance in the DOM by a specified amount of time. This is useful for managing UI transitions or waiting for specific application states before showing content.

    To use it, wrap your content in <RenderAfter> and provide a delay prop representing the time in milliseconds to wait before rendering the children.

    import { RenderAfter } from 'react-haiku';
    
    export const Component = () => {
        return(
            <RenderAfter delay={5000}>
                <b>Wait 5 seconds and I'll show up!</b>
            </RenderAfter>
        );
    }
  7. Install react-haiku via npm, yarn, or pnpm

    main

    Haiku is a lightweight collection of React Hooks and Utilities. To use it in your project, install the react-haiku package using your preferred package manager.

    Requirement: React version 16.8.0 or higher.

    npm install react-haiku
    # or
    yarn add react-haiku
    # or
    pnpm install react-haiku
  8. Use the useIdle hook to detect user inactivity

    main

    The useIdle() hook monitors user activity on a web page and returns a boolean indicating whether the user is currently idle. A user is considered idle when no specified activity events are triggered within the provided timeout period.

    Basic Usage

    Pass a timeout in milliseconds to define how long the user must be inactive before the state switches to true (idle).

    import { useIdle } from "react-haiku"
    
    export const Component = () => {
        // Returns true after 3000ms of inactivity
        const idle = useIdle(3000);
    
        return <b>Current Status: {idle ? 'Idle' : 'Active'}</b>
    }
    import { useIdle } from "react-haiku"
    
    export const Component = () => {
        const idle = useIdle(3000);
    
        return <b>Current Status: {idle ? 'Idle' : 'Active'}</b>
    }