0

I have used JQuery inside my React functional component to select nodes that have a specific tag + class, just like in CSS, but can I do something similar with React besides the Javascript classic way? For example, if I have an unordered list who has an element with the class "active", I can remove his class like so with JQuery:

  $("ul li.active").removeClass("active");

With what I have found by now, with React something similar would be:

let element = document.getElementByClassName("active")
ReactDOM.findDOMNode(element).classList.remove("active"); 

Obviously the two methods are not equivalent, because in the JQuery one I also specified I want the node to be a li with class active who is a child of ul, so I would probably need to write 2 more lines for it to match the JQuery command.

Is it a shorter or better way of doing this, and also is it OK to use JQuery inside React?

3
  • Ref: Document.querySelectorAll() Commented Jun 1, 2021 at 7:25
  • " is it OK to use JQuery inside React" Not the best practice, but it won't break your design. Commented Jun 1, 2021 at 7:29
  • @Yoshi you're right, thank you. Commented Jun 1, 2021 at 7:33

1 Answer 1

2

React discourages the use of direct DOM manipulation. It is fragile and can break when a component is re-rendered.

You should store the selected items in the state and generate class names based on that.

const items = [
  {
    name: "one",
  },
  {
    name: "two",
  },
  {
    name: "three",
  },
];

const App = () => {
  const [selected, updateSelected] = React.useState(["two"]);

  return (
    <div>
      {items.map((item) => (
        <button
          className={selected.includes(item.name) && "selected"}
          onClick={() => {
            if (selected.includes(item.name))
              updateSelected(selected.filter((name) => name !== item.name));
            else updateSelected([...selected, item.name]);
          }}
        >
          {item.name}
        </button>
      ))}
    </div>
  );
};

ReactDOM.render(<App/>, document.body);
.selected { background: blue; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.