Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Render based on state (rather than directly DOM manipulate) #11

Open
oliverjam opened this issue Sep 18, 2020 · 0 comments
Open

Render based on state (rather than directly DOM manipulate) #11

oliverjam opened this issue Sep 18, 2020 · 0 comments

Comments

@oliverjam
Copy link

<button onClick={(event) => {
if (event.target.className === "user-card hidden"){
event.target.classList.remove("hidden");
event.target.classList.add("flipped");
} else{
event.target.parentNode.classList.remove("hidden");
event.target.parentNode.classList.add("flipped");
}

This is kind of a subtle React philosophy thing, but you should generally be suspicious if your code ever has to touch the real DOM. React is designed to handle all DOM updates for you, so if you're ever doing a querySelector or directly changing classNames etc that's usually something to avoid.

Remember your component re-runs whenever state changes, which means you can put conditions and dynamic stuff into your JSX to determine e.g. what classNames elements should have. You just need to have state values that let you know what to render.

E.g. if you kept track of the selected cards in state you could then declaratively render your UI based on that state:

const [selectedCards, setSelectedCards] = React.useState([]);

{data.map(user => (
  <button
    className={selectedCards.includes(user) ? "flipped" : "hidden"}
    onClick={() => putUserIntoSelectedCardsSomehow(user)}
  >
  {user}
  </button>
)}

Generally React updates are a lot easier to manage if you do as little logic as possible in event handlers and try to just make them simple state updates. You can then use the updated state in your render to determine what the page should look like.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant