Reputation: 25
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?
Upvotes: 0
Views: 324
Reputation: 944445
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>
Upvotes: 2