fac19 / week10-Chlat

https://lets-go-pokemon-battle.netlify.app/
1 stars 0 forks source link

Accessing the DOM vs the virtual DOM #22

Open matthewdking opened 4 years ago

matthewdking commented 4 years ago

In React you are using a virtual DOM that React uses to render updates quickly. I would suggest using the virtual DOM at all times, this means not accessing the actual DOM using APIs such as document.querySelector. When using something like document.querySelector it will search at a DOM level rather than component level and therefore could return unexpected results.

This may not be a problem here but in a bigger codebase so I thought it worth mentioning. There is an alternative...

Using refs (see the docs) would solve this issue.

The following is semi pseudo code I didn't check it would run 🙃

const AudioComponent = ({ src }) => {
  const audioRef = React.useRef(null);

  const playAudio = () => {
    const audio = audioRef.current;
    if (audio.paused) {
      audio.play();
    } else {
      audio.pause();
      audio.currentTime = 0;
    }
  };

  return (
    <audio ref={audioRef} >
      <source src={src}></source>
    </audio>
  );
};
oliverjam commented 4 years ago

Good advice. We didn't cover refs, but they're a way to get a reference to a DOM element without having to query the DOM directly.

Meta code-review: you probably want the ref={audioRef} on the <audio>, not the <source>

matthewdking commented 4 years ago

Ooh yeah great spot @oliverjam will edit