2021-03-27

React - is the following true about how html tags' attribute values change when a component is reexecuted?

Can I verify my observation (based on the code below)?:

  1. Class values of an element added in the html markup of a component don't neccessarily 'persist' - when the component is re-executed (perhaps as the result of a change in state), the class value from the last execution can disappear.

  2. However, class values written via vanilla JS persist.

  3. I'm always looking for best practices in code to avoid problems down the line. Is this code a reasonable way to add a class to a tag in React?

sandbox: https://codesandbox.io/s/purple-moon-epmmu?file=/src/styles.css:59-126

import "./styles.css";
import React, { useState, useEffect } from "react";

export default function App() {
  let [color, setColor] = useState(false);

  function updateColor() {
    if (color) {
      setColor("");
    } else {
      setColor("red");
    }
  }

  useEffect(() => {
    document.querySelector(`div`).classList.add(`green-text`);
  }, []);

  return (
    <>
      <div className={color ? "red" : null} onClick={updateColor}>
        Click to add/remove red class
      </div>
    </>
  );
}
.red {
  background-color: red;
}

.green-text {
  color: green;
}


from Recent Questions - Stack Overflow https://ift.tt/3deyCKc
https://ift.tt/eA8V8J

No comments:

Post a Comment