fac18 / react_game-rosa-pat-

react game
https://react-game-pat-and-rosa.netlify.com/
0 stars 2 forks source link

DOM manipulation and React #20

Open oliverjam opened 4 years ago

oliverjam commented 4 years ago

https://github.com/fac18/react_game-rosa-pat-/blob/e0eee8d41bb68880531ce7833887a790fd3b17b5/src/components/cards.js#L19-L25

Again your solution is clever, and it works, but it's not really the "React way". You're accessing the DOM directly to toggle classNames and compare IDs of elements. This works for a small case like this, but quickly gets hard to manage. You can also get hard-to-find bugs because React expects to be in charge of DOM updates.

The "React way" to toggle classNames is to do it declaratively, rather than imperatively (your rendered HTML should be based on the state, rather than manually updating the HTML when you know state has changed). JSX gives us the ability to set values conditionally:

<div className={true ? "clicked" : "not-clicked"}>hello</div>

This means you don't have to directly access and store DOM elements (like you are with event.target.parentElement)—you have access to it within the JSX and can set whatever properties you need right there.