Abdul R.
Abdul R.

Reputation: 290

How to properly add and use third party/npm libraries in Reactjs?

I'm learning react and it's my first time using a library in react. I'm trying to use watermark-js. I've read articles about how I to add npm packages in my react package.json using npm install <library name> save. Here is the part of package.json which show the watermarkjs

"dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-scripts": "2.1.8",
    "save": "^2.4.0",
    "watermarkjs": "^2.0.0"

Now in my App.js component I've imported it as a module and use the snippet provided by watermarkjs in componentDidMount method as in react documentation. below is my complete App.js component.

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Form from './Components/Form';
import ImageWaterMark from './Components/ImageWaterMark';
import image1 from './test-image.jpg'
import image2 from './download.jpg'
import { watermark } from 'watermarkjs'
class App extends Component {

  componentDidMount() {

    //Snippit 

    watermark([{ image1 }, { image2 }])
      .image(watermark.image.lowerRight(0.5))
      .then(function (img) {
        document.getElementById('lower-right').appendChild(img);
      });
  }
  render() {


    return (
      <div className="App">
        <div ref="water"></div>
      </div>
    );
  }
}

export default App;

There are 2 problem that I can't seem to understand. first

How can I pass this snippet as a ref to the render method as in documentation?

Second the App through the following error

TypeError: Cannot read property 'watermark' of undefined

I've read many articles and watched videos but I haven't understand the concept of using libraries. Any help would be much appreciated.

Upvotes: 0

Views: 634

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 84902

watermarkjs uses a default export, not a named export. Change this:

import { watermark } from 'watermarkjs'`

To this:

import watermark from 'watermarkjs'

As for how to use it, once it loads you should call setState with the result. This will render your component again, and you can use that value however you see fit. For example:

  componentDidMount() {
    watermark([{ image1 }, { image2 }])
      .image(watermark.image.lowerRight(0.5))
      .then((img) => {
        this.setState({ img });
      });
  }

  render() {
    return (
      <div className="App">
        <div ref="water">
          {this.state.img && /* whatever you want to do with the image */ }
        </div>
      </div>
    );
  }

I'm not exactly sure what img resolves to, so don't know exactly what you'd put in the render function. If it's url string, it would be {this.state.img && <image src={this.state.img} />}

Upvotes: 1

Related Questions