I am struggling to convert my normal jQuery code in to React JS (I'm new to React).
I have the following code:
$(".add").click(function () {
    $("nav").addClass("show");
});
$(".remove").click(function () {
    $("nav").removeClass("show");
});
$(".toggle").click(function () {
    $("nav").toggleClass("show");
});
nav {
  width: 250px;
  height: 150px;
  background: #eee;
  padding: 15px;
  margin-top: 15px;
}
nav.show {
  background: red;
  color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<button class="add">Add</button>
<button class="remove">Remove</button>
<button class="toggle">Toggle</button>
<nav>Navigation menu</nav>
Tried references seems that only add/remove class for the same element:
https://stackoverflow.com/a/42630743/6191987
How to add or remove a className on event in ReactJS?
So, how can I convert or create the same jQuery methods to ReactJS?
You could check this sandbox link for implementation
function App() {
  const [show, setShow] = React.useState();
  return (
    <div className="App">
      <button className="add" onClick={() => setShow(true)}>
        Add
      </button>
      <button className="remove" onClick={() => setShow(false)}>
        Remove
      </button>
      <button className="toggle" onClick={() => setShow(!show)}>
        Toggle
      </button>
      <nav className={show ? "show" : ""}>Navigation menu</nav>
    </div>
  );
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With