svgdotjs / svg.js

The lightweight library for manipulating and animating SVG
https://svgjs.dev
Other
11.04k stars 1.08k forks source link

Can't run SVG() in Next.js #1159

Closed m-hagberg closed 3 years ago

m-hagberg commented 3 years ago

Bug report

I can't get SVG.js to run in a Next.js project I'm working on (with Typescript).

I've tried multiple different ways, from the super-minimal approach below, to using React.FC as a separate component.

Fiddle

https://repl.it/@pestbarn/PeachpuffDutifulHashmaps#pages/index.tsx (might take a minute to compile)

Explanation

TypeError: Cannot read property 'Node' of null
import { SVG } from '@svgdotjs/svg.js'

export default function Home() {
  let draw = SVG().addTo('#draw')
  draw.rect(150,100).fill('#f03')

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

Callstack: https://pastebin.com/xXSt6xab

Fuzzyma commented 3 years ago

I don't know how to integrate a Dom Library into react but I am pretty sure there is a hook which tells you that the element is mounted and available. You are trying to add the svg to the node before you even returned it. How is it supposed to exist at this point?

So, the node is not in the Dom when you call svg. Make sure that the node exists in the dom

m-hagberg commented 3 years ago

Thanks, you're absolutely right. Been quite a few years since I've worked with React, so I'm still getting used to the lifecycle stuff.

Using the Effect hook worked perfectly, everything is executing as expected.

const Animation: React.FC = () => {
  useEffect(() => {
    let draw = SVG().addTo('#draw')
    draw.rect(150,100).fill('#f03')
  })

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