Search code examples
reactjsnpmnpm-package

Not able to use NPM package in React


I want to use TagCloud in my React app but I am not able to get it to work. I don't get any error message in the console, it just doesn't appear. I used the same code in plain HTML and JS and it worked there

I had to import the package in another way due to this error:

Could not find a declaration file for module 'TagCloud'. 'D:/Javascript/portfolio/node_modules/TagCloud/dist/TagCloud.js' implicitly has an 'any' type.

This is my React component

import React from 'react';
import './about.scss';

function About() {
  const TagCloud = require('TagCloud');
  const Tags = [
    'JavaScript',
    'CSS',
    'HTML',
    'Vscode',
    'XD',
    'React',
    'Python',
    'Linux',
    'git',
    'Flutter',
    'Dart',
    'Firebase',
    'SASS',
    'JSON',
    'Figma',
  ];

  TagCloud('.content', Tags, {
    radius: 250,
    maxSpeed: 'fast',
    initSpeed: 'fast',
    direction: 135,
    keep: true,
  });
  
  return (
    <div className="About" id="About">
      <div className="left">
        <div className="heading">
          <h1>ABOUT</h1>
        </div>
      </div>
      <div className="right">
        <span className=".content">
        </span>
      </div>
    </div>
  );
}

export default About;

Solution

  • import React, { useEffect, useRef } from 'react'
    import TagCloud from 'TagCloud'
    
    const Tags = [
        'JavaScript',
        'CSS',
        'HTML',
        'Vscode',
        'XD',
        'React',
        'Python',
        'Linux',
        'git',
        'Flutter',
        'Dart',
        'Firebase',
        'SASS',
        'JSON',
        'Figma',
    ]
    
    function App() {
        const IsTagCloudLoaded = useRef(false)
    
        useEffect(() => {
            if (IsTagCloudLoaded.current) return
    
            TagCloud('.content', Tags, {
                radius: 250,
                maxSpeed: 'fast',
                initSpeed: 'fast',
                direction: 135,
                keep: true,
            })
    
            IsTagCloudLoaded.current = true
        }, [])
    
        return (
            <div className='About' id='About'>
                <div className='left'>
                    <div className='heading'>
                        <h1>ABOUT</h1>
                    </div>
                </div>
                <div className='right'>
                    <div className='content' />
                </div>
            </div>
        )
    }
    
    export default App
    

    Result

    Result