Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS onclick add or remove class to another element

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?

like image 370
vishnu Avatar asked Jan 25 '23 19:01

vishnu


1 Answers

  1. Use the state that keeps the track of whether to show the nav or not.
  2. Use a class name in the react code that corresponds to the state.
  3. React uses "className" instead of "class" since "class" is already a reserved word in javascript.

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>
  );
}
like image 160
Prateek Thapa Avatar answered Jan 27 '23 07:01

Prateek Thapa