For enquiries call:

Phone

+1-469-442-0620

HomeBlogWeb DevelopmentHow to Set Up and Use Particles.js in React Projects?

How to Set Up and Use Particles.js in React Projects?

Published
30th Oct, 2023
Views
view count loader
Read it in
14 Mins
In this article
    How to Set Up and Use Particles.js in React Projects?

    Have you ever thought about how some developers can create stunning background animations like fireworks, confetti, night sky with blinking stars, etc.? Well, the same thing happened to me when I was looking at a welcome page made by a developer with a nice blinking animation as its background.

    The name of the package is Particle JS React which is a lightweight, dependency-free, responsive, and flexible JavaScript plugin that is used to create 2D animations like the ones mentioned above.

    In this article, we are going to use Particle.js in React with a little twist. The twist is that we will use the typescript version of React Particle JS as it is lightweight, flexible, and easy to use compared to the JavaScript version of Particle JS. This typescript version is specifically made for component-based frameworks and libraries of JavaScript like React, Angular, and Vue and is generally called Tsparticles and for React – React Tsparticles

    If you want to use npm packages or libraries like these in your React App, you have first to understand React step by step and to understand something step by step, we need to have a guide of some kind as there are many things available on the internet nowadays and without a guide or a syllabus to start things with we can easily drift away in this sea of data. Thus introducing React JS syllabus for your smooth navigation of this amazing JavaScript Library, with the help of which you can make animations like these and do other cool stuff very easily.

    Let's create an App that contains a stunning background animation of a starry night sky with the help of particle JS in React. 

    Index 

    1. Introduction of Particle JS 
    2. Creating the React App 
    3. Installing Particle JS library 
    4. Importing the library in our app  
    5. Working on the App 
    6. Conclusion 

    Introducing Tsparticle.JS

    Before moving forward with our app, let's take an overview of the library - Tsparticle that we will be using in this app to make an excellent background animation. 

    Below is the GIF of the website - Tsparticle where we can see the stunning background animation in action. On the right-hand side on top, we have an options tab which we will also be made in our project.

    introducing tsparticlesjs

    With this demo website, we can see many options that we are free to use in our app and what all properties and values they have that we can adjust to our needs.

    All in all, this demo website is yours to play around with. You can try all of the things and see what effects it has without having to understand how it works. 

    Creating the React App

    It's very easy to create a React app – go to your working directory in your preferred IDE and enter the following command in the terminal:

    npx create-react-app starry-night 

    If you are unsure how to properly set up a create-react-app project, you can refer to the official guide here at create-react-app-dev.‌‌ 

    After the setup, run npm start in the same terminal to start localhost:3000 where our React app will be hosted. We can also see all our changes there.

    Installing the React Particle JS library 

    To start using the Particles JS in React, we must first install its typescript version, as this version is only made for component-based libraries and frameworks like React and is much simpler to use than the actual one.  

    To install it, run the following command in the command prompt or terminal which is already running at the back of the project we have just created. 

    For npm users 
    npm i react-tsparticles  
    npm i tsparticles 

    For yarn users 

    yarn add react-tsparticles 
    yarn add tsparticles 

    We can also install the react-tsparticles while creating our react app with the below-given command 

    $ create-react-app your_app --template particles 

    or 

    $ create-react-app your_app --template particles-typescript 

    If any legacy error shows, use –force for npm users, as this will force update everything  

    npm i react-tsparticles –force 
    npm i tsparticles –force 

    Importing the Particles JS Library in our App

    Just like any other package, we first have to import the Tsparticle library from the node modules in the App.js file so that we can start using it.

    import React from "react"; 
    import Particles from "react-tsparticles"; 
    import { loadFull } from "tsparticles"; 
    const App = () => { 
      return <div>Hello</div>; 
    }; 
    export default App; 

    Working on the UI part of the App

    Now that we are done with our prerequisites, like installing and importing the tsparticles packages, we can start working with its Particle component, which we have already imported into our app. This Particle component acts just like an HTML Canvas Element. This means we can make any animation with it and manipulate it with the help of JavaScript and that is exactly what we will be doing in this project.

    Before working on this Particle Component, one thing to note is that here we can only give data in the JSON format that is in the form of key and value pairs. But even before that, we have to pass some props to our Particle component to link it with our react-tsparticles and tsparticles library.

    import React from "react"; 
    import Particles from "react-tsparticles"; 
    import { loadFull } from "tsparticles"; 
    const App = () => { 
      return ( 
        <> 
          <Particles 
            id="tsparticles" 
            init={particlesInit} 
            loaded={particlesLoaded} 
          /> 
        </> 
      ); 
    }; 
    export default App; 

    Let's begin entering the data in the form of key and value pairs as told and make the most beautiful starry night sky app with React and Particle JS. 

    This Particle Component has options attribute that marks the beginning of an object which takes react particles js background property as its key with RGB(10, 10, 25) as the value which, as the name suggests, lets us choose the background color of our app. In our case, it is dark blue. 

    Followed by the fpslimit property which is at the same level as the background and set to 60. FPS is just the rate at which we want our app to calculate and display the animations that we have given it.

    import React from "react"; 
    import Particles from "react-tsparticles"; 
    import { loadFull } from "tsparticles"; 
    const App = () => { 
      return ( 
        <> 
          <Particles 
            id="tsparticles" 
            init={particlesInit} 
            loaded={particlesLoaded} 
            options={{ 
              background: { 
                color: "rgb(10,10,25)", 
              }, 
              fpsLimit: 60, 
            }} 
          /> 
        </> 
      ); 
    }; 
    export default App; 

    After setting up the background of the app, it's time to proceed with the stars. Just like the background property was used to set values of the background of the app, the particle property will be used to set the values of the particles that we want our app to have in its background. For the app, we have chosen the star of white color and a shape of a circle as the star shape is not yet available for us to use.

    Let's start the particle property with the shape as the key and circle as its value, followed by the size property, which we will set to a maximum value of 1.4, which points out to another object with random as its key and pointing to another new object with minimum value as key and 0.05 as its value. Simply said saying the size of our star particle can be random but should start from 0.05 and end at 1.4. 

    Next comes the color property which no doubt should be set to either white or off-white as it should come in contrast with the background to give us that night sky feeling. Now that we have conquered the two most difficult tasks which are deciding the shape and size and color of the star, it is time to work on its number property. 

    By number, I mean how many stars we want our app to display at a time which we have set to 400. As always, this number property points to another object containing many key and value pairs starting with density which is set to true with an additional key of the area with a value of 1080 depicting the max screen size. The density property is used to make the number of stars also responsive. That is, the number of stars will increase and decrease depending on the screen size and the device on which we are viewing the app. 

    After the number property, it’s time to set the opacity of the particles. The opacity property is used as a key that lets us enter the world of animation, which also has some values that we have to set for the react particle animation to work, starting with the speed property. As the name suggests, this property is used to set the pace at which we want the starry particles to blink, which we have set to 1.6, followed by the minimum value and sync feature, which we have set to 0.5 and false, respectively as we don’t want all the stars to be in sync. 

    This opacity key will also have a random object with the same level as animation which will be enabled true so that the animations can take place at a random rate - to give the stars an actual blinking effect with the minimum value of 0.1.

    And finally, the last piece that will connect all these values – is the interactivity property. This property will not only bind all the above options but also let us interact with them, like adding new stars with a single click or removing stars on hover, etc. But we won't be doing all that as it will affect the night sky's beauty and randomness. The thing we will be doing with it is just setting the screen to responsive as we did in the above section, but this time we will be binding both the background and particle properties as we want to see stars evenly spread across the screen no matter the device.

    import React from "react"; 
    import Particles from "react-tsparticles"; 
    import { loadFull } from "tsparticles"; 
    const App = () => { 
      return ( 
        <div className="App"> 
          <Particles 
            id="tsparticles" 
            init={particlesInit} 
            loaded={particlesLoaded} 
            options={{ 
              background: { 
                color: "rgb(10,10,25)", 
              }, 
              fpsLimit: 60, 
              particles: { 
                shape: { 
                  type: "circle", 
                }, 
                size: { 
                  random: { 
                    enable: true, 
                    minimumValue: 0.5, 
                  }, 
                  value: 1.4, 
                }, 
                color: { 
                  value: "#f1f1f1", 
                }, 
                number: { 
                  density: { 
                    enable: true, 
                    area: 1080, 
                  }, 
                  limit: 0, 
                  value: 800, 
                }, 
                opacity: { 
                  animation: { 
                    enable: true, 
                    minimumValue: 0.5, 
                    speed: 1.6, 
                    sync: false, 
                  }, 
                  random: { 
                    enable: true, 
                    minimumValue: 0.1, 
                  }, 
                  value: 1, 
                }, 
                interactivity: { 
                  detectsOn: "canvas", 
                  events: { 
                    resize: true, 
                  }, 
                }, 
              }, 
            }} 
          /> 
        </div> 
      ); 
    }; 
    export default App; 

    Working on the functionality of our App

    In the beginning, we used some props to connect the app with the tsparticles package but never did so. In this section, we will see how easily we can connect the app with the package and get our animations working without writing any complex code.

    As we are fetching these data from a JSON file, we have to use the async and await feature to asynchronously call every piece of data. We are not only calling the data asynchronously from the JSON file, but the engine as well which is the key component of the animation as this will put everything in motion. This engine will be called from the loadFull feature of the tsparticles package which we have installed with the react-tsparticles package. 

    But that is not all we also need a container to wrap these animations and everything else to ensure that everything is in its proper place and is running properly as we have coded it to run.

    import React from "react"; 
    import Particles from "react-tsparticles"; 
    import { loadFull } from "tsparticles"; 
    const App = () => { 
      const particlesInit = async (main) => { 
        console.log(main); 
        // you can initialize the tsParticles instance (main) here, adding custom shapes or presets 
        // this loads the tsparticles package bundle, it's the easiest method for getting everything ready 
        // starting from v2 you can add only the features you need reducing the bundle size 
        await loadFull(main); 
      }; 
      const particlesLoaded = (container) => { 
        console.log(container); 
      }; 
      return ( 
        <div className="App"> 
          <Particles 
            id="tsparticles" 
            init={particlesInit} 
            loaded={particlesLoaded} 
            options={{ 
              background: { 
                color: "rgb(10,10,25)", 
              }, 
              fpsLimit: 60, 
              particles: { 
                shape: { 
                  type: "circle", 
                }, 
                size: { 
                  random: { 
                    enable: true, 
                    minimumValue: 0.5, 
                  }, 
                  value: 1.4, 
                }, 
                color: { 
                  value: "#f1f1f1", 
                }, 
                number: { 
                  density: { 
                    enable: true, 
                    area: 1080, 
                  }, 
                  limit: 0, 
                  value: 800, 
                }, 
                opacity: { 
                  animation: { 
                    enable: true, 
                    minimumValue: 0.5, 
                    speed: 1.6, 
                    sync: false, 
                  }, 
                  random: { 
                    enable: true, 
                    minimumValue: 0.1, 
                  }, 
                  value: 1, 
                }, 
                interactivity: { 
                  detectsOn: "canvas", 
                  events: { 
                    resize: true, 
                  }, 
                }, 
              }, 
            }} 
          /> 
        </div> 
      ); 
    }  
    export default App; 

    Ultimately, this is how our app looks stunning, isn’t it? 

    working on the working of our App

    You can also make more animations like these just follow along with the React JS syllabus by KnowledgeHut’s and become a react developer online who can make react particles animations equal to or even greater than this.

    We can make many more exciting features like these with the Particle.js library to see all the other cool background effects we can give our app or you can even search for React JS particles background or click here to see other amazing examples of backgrounds that you can make using React JS particles.

    Looking to enhance your skills? Explore our online computer programming certificate courses. Gain expertise in programming and boost your career. Enroll now!

    Conclusion

    In the end, I would say that both of these packages - Particle.JS and Tsparticle.JS has given us the hope of making complex animations like the starry-night sky which we have made in this blog easily rather than complex CSS and JavaScript code.

    Well, this library was initially used for JavaScript but was molded so it can be used in component-based frameworks like React, Angular, and Vue. But if you want you can even make animation like these with pure JavaScript and also gets a certificate for it with our online Web Development Course with a certificate and become a certified web developer online and at your own pace.

    Frequently Asked Questions (FAQs)

    1What are particles in react?

    Particle.JS is a lightweight, dependency-free, responsive, and flexible JavaScript plugin which is used to create 2D animations in JavaScript and we can use its TypeScript version in Component-based frameworks like React to add these 2D animations with ease and without writing a lot of complex JavaScript code.

    2How do you use TS particles in react?

    Just like any other npm package and library, we have to install the tsparticle package in our app using either yarn add react-tsparticles or npm I react-tsparticles and then import it from the node modules in our existing app and directory. 

    3What are Tsparticles?

    Tsparticles is one of the perfect background animation libraries with diverse ways to move those fancy particles that we have used in our animation. It is extremely flexible and made to fit any background no matter the type of website.

    Profile

    Ateev Duggal

    Blog Author

    "I am Ateev Duggal, a front-end web developer, and a blogger. I write blogs mainly on React JS and have an experience of over 1.5 years of freelancing. I have worked on both static and dynamic projects again using React JS like a table to show clients data which was fetched using API, a review slider, pagination component, etc, and many websites like Parent, landing pages for Ataota, and many more.
    Some of my blogs have been published on freecodecamp, dev.to, Medium, Hashnode, and many other blogging platforms and developer's communities.
    My Primary skills not only include React JS but HTML5, CSS3, JS, Jquery, Git, and Bootstrap also. You can visit my GitHub Profile and LinkedIn profile for more information about me or you can visit my Website at tekolio.com".

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon