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) #18

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

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

oliverjam opened this issue Sep 18, 2020 · 0 comments

Comments

@oliverjam
Copy link

if (event.target.textContent === correct_answer) {
event.target.className = "green";
setTimeLeft(timeLeft + 5);
props.setScore(props.score + 1)
} else {
event.target.className = "red";
setTimeLeft(timeLeft - 2);
}

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.

{shuffledChoices.map(choice => (
  <button
    // if we have chosen this button, then if the answer is correct make it green otherwise red
    className={selectedChoice === choice && (selectedChoice === correct_answer ? "green" : "red")}
    onClick ={() =>{
      setSelectedChoice(choice); // store the selected choice in state
      setIndex(index + 1)
    }}
  >
    {choice}
  </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