I am trying to use 3rd party package ReactPhotoSphereViewer
in NextJs to display panoramic images in the website.
The package works both in NextJs and in ReactJs.
Here is the code that is works in ReactJs:
import { ReactPhotoSphereViewer } from 'react-photo-sphere-viewer';
import React, {createRef, useEffect} from 'react';
...
function PanoramaImage({src}) {
return (
<ReactPhotoSphereViewer
src={src}
></ReactPhotoSphereViewer>
);
}
...
export default PanoramaImage;
Here is the code for same purpose in NextJs:
import React, {createRef, useEffect} from "react";
import dynamic from 'next/dynamic'
const ReactPhotoSphereViewer = dynamic(
() =>
import('react-photo-sphere-viewer').then(
(mod) => mod.ReactPhotoSphereViewer
),
{
ssr: false,
}
)
...
function PanoramaImage({src}) {
return (
<div>
<ReactPhotoSphereViewer
src={src}
></ReactPhotoSphereViewer>
</div>
)
}
...
export default PanoramaImage;
However when I tried to add reference to the ReactPhotoSphereViewer
component, it works in ReactJs, but not in NextJs.
Here is the code after adding reference.
...
function PanoramaImage({src}) {
const photoSphereRef = createRef(<ReactPhotoSphereViewer />);
React.useEffect(() => {
if (!photoSphereRef.current)
return;
photoSphereRef.current.toggleAutorotate();
}, [photoSphereRef]);
return (
<div>
<ReactPhotoSphereViewer
ref={photoSphereRef}
src={src}
></ReactPhotoSphereViewer>
</div>
)
}
...
export default PanoramaImage;
I think the problem is createRef hook here. So, is there any method that I can use instead of createRef, or if I am using it wrong, how should it be correct.
I would be glad if you help. Thank you.
edit: The problem is not on the createRef, I used useRef instead of createRef for both ReactJs and NextJs frameworks, ReactJs works perfectly, but I don’t know why, NextJs does not detect the reference.
Finally I gave up using NextJs and start working with ReactJs.
Thank you for everybody.
2
Answers
Use useRef hook.
The difference is that createRef will create a new ref on render.
With functional components you need the same ref each time. useRef does it.
Source: NPM
Or take a look at this code sandbox: https://codesandbox.io/s/sandbox-react-photo-sphere-viewer-by-elius94-j064sm?file=/src/App.js
(Credit to original author elius94)