Email

ParticleJS in React

To get the nice animation you see in the banners of the website, simply look at this post, we'll give you the code and you can stick around to see the explanation.

Dependancies

npm i --save @tsparticles/react @tsparticles/slim

First we've gotta install the packages required, we're using react, so we'll install the react version.

Other versions are supported: https://particles.js.org/

The component itself

"use client"

import { useEffect, useState, type ReactNode } from "react"
import Particles, { initParticlesEngine } from "@tsparticles/react"
import {
  type ISourceOptions,
  MoveDirection,
  OutMode,
} from "@tsparticles/engine"

import { loadSlim } from "@tsparticles/slim"

const ParticlesBG = (): ReactNode => {

  const [init, setInit] = useState(false)

  useEffect(() => {
    initParticlesEngine(async (engine) => {
      await loadSlim(engine)
    }).then(() => {
      setInit(true)
    })
  }, [])

  const options: {...}

  if (init) {
    return (
      <Particles
        className="absolute top-0 left-0 bottom-0 right-0 z-[-2]"
        id="tsparticles"
        options={options}
      />
    )
  }

  return <></>
}

export default ParticlesBG

This is going to be a client component as we need to sequence a couple of things once the Dom has Load so we add "use client" directive at the top of our component.

We then need to import a couple of hooks from React, primarily, useState and useEffect

We want to init our particle engine first, so we we listen for the complete page view with a blank dependancy on useEffect.

Once particle engine is loaded with the slim package, we set our init value to true and this will display our Particles component, where options is your own config.

Using this component

import Particles from "@/components/particles"


const Banner = () => {
  return (
    <section
      className="..."
    >
      <Particles />
    </section>
  )
}

export default Banner

To use, simply import it to your component, and it will work without any fuss!

Get in touch

I am always free to discuss new projects, opportunities or any assistance you may require.

Responses usually take less than 24 hours.