Company News
October 14, 2020

Introducing the Libpixel React hook

We’re always focused on making it easier for you to integrate LibPixel in your projects. Consequently, we have decided to release a much needed React hook that will make it easy for you to use LibPixel in your React projects.

You can install it with npm and you are good to go to using LibPixel urls in your react app. Using the hook, you can select multiple image sources to tackle redundancy and easily customize how the image should output by adjusting the parameters of the image. The hook supports all of the customizations that have been mentioned in our documentation.

The hook is an extension of the react-image package that provides a replacement for the native <img> tag in react. The LibPixel hook has no external dependencies other than React and React-Dom, which you should already have if you are building a React app. 

Here’s a brief demo of the React hook to show you how it works. First, install the hook with the following command: 

  • npm install react-libpixel --save

Now you can create a React functional component that returns a valid <img> tag similar to the following code: 

const PixelsExample = (e) => {
    const { src, isLoading, error } = usePixel({
        srcList: 'http://example-repo.libpx.com/images/sample_img.jpg',
        pixelParams: {
            mode: 'stretch',
            crop: {
                x: 0,
                y: 0,
                w: 300,
                h: 300,
            },
            blur: 2,
            brightness: 50,
            format: 'png',
        },
    });
    return React.createElement("img", { src: src });
};


This functional component uses the usePixel() hook to accept an image source and make some changes to it before returning an <img> tag. 

The following code shows how you can call this function: 

function App() {
 return (
  <>
   <div>
     <h5>LibPixel Example</h5>
     <ErrorBoundary onError={<div>Suspense... wont load</div>}>
      <Suspense fallback={<div>Loading... (Suspense fallback)</div>}>
       <PixelsExample />
      </Suspense>
    </ErrorBoundary>
   </div>
  </>
    )
}

This is a simple app that calls the PixelsExample() functional component to show an image on a page. A best practice is to enclose the component in Suspense() and ErrorBoundary() to make a robust application that covers all the cases.

What’s More

With the React hook, you can easily integrate LibPixel valid URLs into your React app and deliver custom images on the go. LibPixel is steadily growing its support for the famous platforms and stacks and we will soon be releasing a similar Vue component. 


Ready to dive in?
Start your free trial today.