react-top-loading-bar

repository·master·Indexed 20 days ago

https://github.com/klendi/react-top-loading-bar

A customizable React top loader component for indicating loading states. Version 3.0.2 provides a LoadingBar component that can be controlled declaratively via a progress prop or imperatively using a ref or the useLoadingBar hook within a LoadingBarContainer. Features include support for continuous and static loading animations, customizable colors, height, and shadow effects, as well as methods to increase, decrease, or complete the progress bar.

Tokens
3.8K
Snippets
9
Records
11
Agent score
23%

What's inside react-top-loading-bar

  1. Migrate from V.1 and V.2

    master

    If you are upgrading from older versions, follow these steps:

    From V.1:

    • Replace the onRef prop with ref. Assign it to a React ref and access methods via reactRef.current.xxx.

    From V.2:

    • Replace ref.current.continuousStart() with ref.current?.start().
    • Replace ref.current.staticStart() with ref.current?.start("static").
  2. Use the useLoadingBar hook

    master

    The useLoadingBar hook provides a simple way to control the loading bar using start and complete functions. When using this hook, you should wrap your application (or the relevant parent component) with LoadingBarContainer to ensure the loading bar renders correctly.

    import { useLoadingBar, LoadingBarContainer } from "react-top-loading-bar";
    
    const App = () => {
      const { start, complete } = useLoadingBar({
        color: "blue",
        height: 2,
      });
    
      return (
        <div>
          <button onClick={() => start()}>Start</button>
          <button onClick={() => complete()}>Complete</button>
        </div>
      );
    };
    
    // Ensure the app is wrapped in LoadingBarContainer
    const Parent = () => {
      return (
        <LoadingBarContainer>
          <App />
        </LoadingBarContainer>
      );
    };
  3. Use LoadingBarContainer and useLoadingBar hook

    master

    For a cleaner architecture (especially in large apps), wrap your application or a section in LoadingBarContainer. This provides a context that allows any child component to control the loading bar using the useLoadingBar hook without passing refs down manually.

    Note: useLoadingBar must be used within a component that is a child of LoadingBarContainer.

    import { LoadingBarContainer, useLoadingBar } from 'react-top-loading-bar';
    
    const ControlPanel = () => {
      // Access methods via hook
      const { start, complete, increase } = useLoadingBar();
    
      return (
        <div>
          <button onClick={() => start('continuous')}>Start</button>
          <button onClick={() => increase(10)}>Add 10%</button>
          <button onClick={complete}>Finish</button>
        </div>
      );
    };
    
    const App = () => (
      <LoadingBarContainer props={{ color: 'blue' }}>
        <ControlPanel />
      </LoadingBarContainer>
    );
  4. Control LoadingBar via State

    master

    For manual progress control, you can pass a progress value (0-100) directly to the LoadingBar component. Use the onLoaderFinished callback to reset your state when the bar reaches 100%.

    import { useState } from "react";
    import LoadingBar from "react-top-loading-bar";
    
    const App = () => {
      const [progress, setProgress] = useState(0);
    
      return (
        <div>
          <LoadingBar
            color="#f11946"
            progress={progress}
            onLoaderFinished={() => setProgress(0)}
          />
          <button onClick={() => setProgress(progress + 10)}>Add 10%</button>
          <button onClick={() => setProgress(progress + 20)}>Add 20%</button>
          <button onClick={() => setProgress(100)}>Complete</button>
        </div>
      );
    };
  5. Control LoadingBar via Ref

    master

    You can control the LoadingBar component directly using a React ref. This gives you access to various built-in methods like continuousStart, staticStart, and complete.

    import { useRef } from "react";
    import LoadingBar, { LoadingBarRef } from "react-top-loading-bar";
    
    const App = () => {
      // prettier-ignore
      const ref = useRef<LoadingBarRef>(null);
    
      return (
        <div>
          <LoadingBar color="#f11946" ref={ref} shadow={true} />
          <button onClick={() => ref.current?.continuousStart()}>
            Start Continuous Loading Bar
          </button>
          <button onClick={() => ref.current?.staticStart()}>
            Start Static Loading Bar
          </button>
          <button onClick={() => ref.current?.complete()}>Complete</button>
        </div>
      );
    };
  6. Reference: LoadingBar built-in methods

    master

    These methods are available via the LoadingBarRef when using a ref or via the object returned by useLoadingBar.

    | Methods | Parameters | Descriptions |
    | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- |
    | start(loaderType?) | `continuous` (default) or `static` | Starts the loading indicator. If type is "static" it will start the static bar otherwise it will start the animated continuous bar. |
    | continuousStart(startingValue, refreshRate) | Number (optional), Number(optional) | Starts the loading indicator with a random starting value between 20-30, then repetitively after an refreshRate, increases it by a random value between 2-10. This continues until it reaches 90% of the indicator's width. |
    | staticStart(startingValue) | Number (optional) | Starts the loading indicator with a random starting value between 30-50. |
    | complete() | | Makes the loading indicator reach 100% of his width and then fade. |
    | increase(value) | Number | Adds a value to the loading indicator. |
    | decrease(value) | Number | Decreases a value to the loading indicator. |
    | getProgress() | | Get the current progress value. |
  7. Reference: LoadingBar properties

    master

    Configuration options for the LoadingBar component.

    | Property | Type | Default | Description |
    | :----------------- | :------------ | :------------ | :-------------------------------------------------------------------------------------------------------------------------------- |
    | progress | Number | `0` | The progress/width indicator, progress prop varies from `0` to `100`. |
    | color | String | `red` | The color of the loading bar, color take values like css property `background:` do, for example `red`, `#000` `rgb(255,0,0)` etc. |
    | shadow | Boolean | `true` | Enables / Disables shadow underneath the loader. |
    | height | Number | `2` | The height of the loading bar in pixels. |
    | background | String | `transparent` | The loader parent background color. |
    | style | CSSProperties | | The style attribute to loader's div |
    | containerStyle | CSSProperties | | The style attribute to loader's container |
    | shadowStyle | CSSProperties | | The style attribute to loader's shadow |
    | transitionTime | Number | `300` | Fade transition time in miliseconds. |
    | loaderSpeed | Number | `500` | Loader transition speed in miliseconds. |
    | waitingTime | Number | `1000` | The delay we wait when bar reaches 100% before we proceed fading the loader out. |
    | className | String | | You can provide a class you'd like to add to the loading bar to add some styles to it |
    | containerClassName | String | | You can provide a class you'd like to add to the loading bar container to add some css styles |
    | onLoaderFinished | Function | | This is called when the loading bar completes, reaches 100% of his width. |
  8. Configure LoadingBar props

    master

    The LoadingBar component accepts the following props to customize its appearance and behavior:

    PropTypeDefaultDescription
    progressnumberundefinedThe current progress percentage (0-100).
    colorstring'red'The color of the loading bar and its shadow.
    heightnumber2The height of the loading bar in pixels.
    backgroundstring'transparent'The background color of the container.
    shadowbooleantrueWhether to show a glowing shadow effect.
    loaderSpeednumber500Speed of transitions in milliseconds.
    transitionTimenumber300Time taken to fade out the bar when finished.
    waitingTimenumber1000Time to wait at 100% before fading out.
    onLoaderFinished() => voidundefinedCallback triggered when the bar finishes and fades out.
    classNamestring''CSS class for the bar element.
    containerClassNamestring''CSS class for the fixed container.
    styleCSSProperties{}Inline styles for the bar element.
    containerStyleCSSProperties{}Inline styles for the container.
    shadowStyleCSSProperties{}Inline styles for the shadow element.
    styleCSSProperties{}Inline styles for the bar element.
  9. Use the LoadingBar component

    master

    The LoadingBar component is the core UI element. It can be controlled either via the progress prop (declarative) or via a ref (imperative).

    Warning: Do not use both simultaneously. If you provide a progress prop, the ref methods will trigger a warning and may not behave as expected.

    import LoadingBar from 'react-top-loading-bar';
    
    // Declarative usage
    <LoadingBar progress={45} color="blue" />
  10. Control LoadingBar via Ref (LoadingBarRef)

    master

    If you are using LoadingBar directly with a ref, you can access these methods to control the animation imperatively:

    • start(type?: 'continuous' | 'static', startingValue?: number, refreshRate?: number): Starts the loader. continuous mode animates automatically; static mode stays at a specific value.
    • continuousStart(startingValue?: number, refreshRate?: number): Specifically starts the continuous animation.
    • staticStart(startingValue?: number): Specifically starts the static animation.
    • complete(): Immediately sets progress to 100% and triggers the finish sequence.
    • increase(value: number): Increases the current progress by the specified amount.
    • decrease(value: number): Decreases the current progress by the specified amount.
    • getProgress(): Returns the current progress value.
    import React, { useRef } from 'react';
    import LoadingBar, { LoadingBarRef } from 'react-top-loading-bar';
    
    const MyComponent = () => {
      const loaderRef = useRef<LoadingBarRef>(null);
    
      const handleStart = () => {
        loaderRef.current?.start('continuous');
      };
    
      return (
        <>
          <button onClick={handleStart}>Start Loading</button>
          <LoadingBar ref={loaderRef} />
        </>
      );
    };