How would you translate this code to javascript react?

Viewed 28

I'm still learning js react and I don't really know how to write this code. I know the equivalent to querySelector in react is useRef but I'm not sure how to use it.

<script>
        let li = document.querySelectorAll(".faq-text li");
        for (var i = 0; i < li.length; i++) {
          li[i].addEventListener("click", (e)=>{
            let clickedLi;
            if(e.target.classList.contains("question-arrow")){
              clickedLi = e.target.parentElement;
            }else{
              clickedLi = e.target.parentElement.parentElement;
            }
           clickedLi.classList.toggle("showAnswer");
          });
        }
</script>
1 Answers

This wouldn't be my go to for using useRef, instead it seems like you're manually managing state and need react to manage the state of which li was clicked for you. To accomplish this you can use the useState hook and create a function which changes state based on which li was clicked. Here is a simple example that hopefully makes it clear for you.

const {useState} = React;

function App(props) {
  const questions = ["q1", "q2", "so on", "so forth"];
  const [selected, setSelected] = useState("q1");
  
  function clickLi(str) {
    setSelected(str);
  }

  return (
      <ul className="faq-text">
        {
          questions.map(str => (
            <li 
              className={str == selected ? "show-answer" : ""} 
              onClick={() => clickLi(str)} 
              key={"faq-" + str}
              > {str} </li>
          ))
        }
      </ul>
  );
}


ReactDOM.createRoot(
  document.getElementById("root")
).render(
  <App />
);
.faq-text {
  list-style: none;
  padding: 0;
}

.faq-text li {
  border: 2px solid blue;
  cursor: pointer;
  
  transition: 0.1s;
}

.faq-text li.show-answer {
  background-color: lightblue;
}

.faq-text li:hover {
  border-color: lightgreen;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

Related