javascriptreactjscolor-thief

Using Color Thief Library in React doesn't work


I am struggling to add Color Thief in a react app. I have followed the instruction on github but nothing changes. I have applied the suggestions reporte here and then inserted the scripts inside a setTimeout function, but I get always the same error:

error

Can you please help me to run this library (or similars if you have alternatives) in react?

Here is my code so far:

import React from 'react';
import './App.css';
var ColorThief = require('color-thief');

function App() {
 setTimeout(function(){
    var colorThief = new ColorThief();
    var img = 'img.jpg';
    var palette = colorThief.getPalette(img, 8);
    var dominant =  colorThief.getColor(img);
    console.log(palette);
    console.log(dominant);
    document.getElementById("app").style.backgroundColor = "rgb(" + dominant + ")";
 }, 3000);

return (
    <div id="app"></div>
 );
}

export default App;

Solution

  • Install the library with npm:

    $ npm i --save colorthief
    

    Import the library in your file as:

    import ColorThief from "colorthief";
    

    Create a react reference to your image like so:

      constructor(props) {
        super(props);
    
        // Image element reference
        this.imgRef = React.createRef();
      }
    

    The image component should look like this:

              <img
                crossOrigin={"anonymous"}
                ref={this.imgRef}
                src={
                  "https://images.unsplash.com/photo-1516876437184-593fda40c7ce"
                }
                alt={"example"}
                className={"example__img"}
                onLoad={() => {
                  const colorThief = new ColorThief();
                  const img = this.imgRef.current;
                  const result = colorThief.getColor(img, 25);
                }}
              />
    

    ( Please note, the image props should be in this exact order)