vishnu
vishnu

Reputation: 2948

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?

Upvotes: 6

Views: 18579

Answers (2)

Prateek Thapa
Prateek Thapa

Reputation: 4938

  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>
  );
}

Upvotes: 8

hgb123
hgb123

Reputation: 14891

You could combine the use useRef for nav and manipulate the ref (accessing nav's DOM) with event handlers for each button

import React from "react";
import "./styles.css";

export default function App() {
  const navRef = React.useRef(null);

  const onAddClick = (e) => {
    navRef.current.classList.add("show");
  };

  const onRemoveClick = (e) => {
    navRef.current.classList.remove("show");
  };

  const onToggleClick = (e) => {
    navRef.current.classList.toggle("show");
  };

  return (
    <div className="App">
      <button onClick={onAddClick}>Add</button>
      <button onClick={onRemoveClick}>Remove</button>
      <button onClick={onToggleClick}>Toggle</button>
      <nav ref={navRef}>Navigation menu</nav>
    </div>
  );
}
.App {
  font-family: sans-serif;
}

nav {
  width: 250px;
  height: 150px;
  background: #eee;
  padding: 15px;
  margin-top: 15px;
}

nav.show {
  background: red;
  color: white;
}

Codesanbox link for demo

Edit objective-framework-lpl9e

Reference:

Upvotes: 5

Related Questions