I am building a preloader using nextjs, it's a timed benzene animation that plays out entirely before the homepage appears. The issue that I am dealing with comes from both ways that I try to implement this preloader. First, when I set the viewbox attributes in the component as shown below, I receive an error.
"use client";
import React, { useEffect, useState } from 'react';
import './Preloader.module.css';
const Preloader = () => {
const viewBox = `${-window.innerWidth / 2} ${-window.innerHeight / 2} ${window.innerWidth} ${window.innerHeight}`;
return (
<div className='preloader-div'>
<svg viewBox={viewBox} width="100%" height="100%">
...
</svg>
</div>
);
};
export default Preloader;
This is the error I receive...
error - ReferenceError: window is not defined
at Preloader (./src/app/preloader/preloader.tsx:13:21)
6 | const Preloader = () => {
7 |
> 8 | const viewBox = `${-window.innerWidth / 2} ${-window.innerHeight / 2} ${window.innerWidth} ${window.innerHeight}`;
So I did some research, and there are a few ways that I would be able to fix this, and the one that worked the best was to use useEffect. It does remove the error but the issue now comes from my svg starting in the top left of the browser for about the first second of the page loading, but then when useEffect runs, it gets moved to the center.
"use client";
import React, { useEffect, useState } from 'react';
import './Preloader.module.css';
const Preloader = () => {
const [viewBox, setViewBox] = useState('');
useEffect(() => {
setViewBox(`${-window.innerWidth / 2} ${-window.innerHeight / 2} ${window.innerWidth} ${window.innerHeight}`);
}, []);
return (
<div className='preloader-div'>
<svg viewBox={viewBox} width="100%" height="100%">
...
</svg>
</div>
);
};
export default Preloader;
How would I remove this error but also have my svg centered from the initial loading of the page?
Via Active questions tagged javascript - Stack Overflow https://ift.tt/6l0UjTt
Comments
Post a Comment