https://codesandbox.io/s/pensive-kirch-21994p?file=/src/App.tsx
const playRef = useRef(null);
const playOrPause = () => {
setIsPlaying((prev) => {
if (playRef) {
playRef.current[prev ? "pause" : "play"]();
}
return !prev;
});
};
can someone please help me fix this type error
React.MutableRefObject<null>.current: null
Object is possibly 'null'.
CodePudding user response:
You need to define the specific type:
Try this:
const playRef = useRef<ImageGallery>(null);
CodePudding user response:
You need to change the if condition and add the type on the useRef like this:
export default function App() {
const playRef = useRef<ImageGallery>(null);
const [isPlaying, setIsPlaying] = useState(false);
const playOrPause = () => {
setIsPlaying((prev) => {
if (playRef.current !== null) {
playRef.current[prev ? "pause" : "play"]();
}
return !prev;
});
};
return (
<div className="App">
<ImageGallery ref={playRef} items={images} showPlayButton={false} />
<button onClick={playOrPause}>{isPlaying ? "Pause" : "Play"}</button>
</div>
);
}