1

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'.
0

2 Answers 2

1

You need to define the specific type:

Try this:

  const playRef = useRef<ImageGallery>(null);
Sign up to request clarification or add additional context in comments.

Comments

1

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>
  );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.