Snap.svg
Snap.svg copied to clipboard
Using Snap SVG with React and Next.js
Hello there,
I'm developing a website using Next.js and React.
I config my next.config.js just like writed in documents and you can watch it in attached files.
and then I imported this line in my js file:
import Snap from 'snapsvg';
.
but I still have an error in my terminal that ReferenceError: window is not defined
.
Can you guys help me fix this?
Did you find a solution? I'm having the same issue that is linked to the use of Snap with an SSR application.
Hello @KudMath
I think the simplest way is that require it only in your componentDidMount()
method. This method called when the page is loaded and you have full access to javascript variables like window
.
componentDidMount = () => {
const Snap = require('snapsvg');
// now you can use Snap!
}
And if you want to access it in your class you can do this:
class UseSnap extend React.Component{
this.snap = null;
componentDidMount = () => {
this.snap = require('snapsvg');
}
}
I hope it will work for you.
Hello - I am still having trouble with this method. Below is my code but I am receiving this error on page load. My code is loaded into a page component.
my error message is
Unhandled Runtime Error
TypeError: Cannot read property 'on' of undefined
Source
.next\static\chunks\pages\svg-test.js (2487:0) @ <unknown>
2485 | };
2486 | // default
> 2487 | eve.on("snap.util.getattr", function () {
2488 | var att = eve.nt();
2489 | att = att.substring(att.lastIndexOf(".") + 1);
2490 | var css = att.replace(/[A-Z]/g, function (letter) {
My next.js.config is:
var webpack = require('webpack')
module.exports = {
module: {
loaders: [{
test: require.resolve('snapsvg'),
loader: 'imports-loader?this=>window,fix=>module.exports=0'
}]
},
images: {
domains: ['www.example.com']
}
}
my page code with my attempt to use snap inside
import React, { Component } from "react";
export class UseSnap extends Component {
constructor() {
super();
this.snap = null;
}
componentDidMount = () => {
if (process.browser) {
const Snap = require("snapsvg");
this.snap = require("snapsvg");
var s = Snap(800, 600);
var s = Snap("#svgout");
var fobjectSVG =
'<svg><foreignObject width="80" height="200"><body><p>Here is a paragraph that requires word wrap</p></body></foreignObject></svg>';
var p = Snap.parse(fobjectSVG);
var g = s.group().append(p);
g.animate({ transform: "t300,0r45,50,50" }, 2000);
}
};
render() {
return <div></div>;
}
}
export default UseSnap;
https://www.npmjs.com/package/snapsvg-cjs-ts