Reputation:
I am working on Reactjs and trying to use jquery ( add class onclick), its working whenever we refresh the page but whenever i come to page after any menu click ( not refresh) then jquery not working ( add class onclick not working),How can i do this ? Here is my current code
$(document).ready(function(){
$(".PrivateSwitchBase-input-6").on('click', function(sss){
$(".MuiFormControlLabel-root").removeClass("active");
$(this).parents('.MuiFormControlLabel-root').addClass("active");
});
});
Upvotes: 1
Views: 337
Reputation: 374
Using Jquery with React at the same time is not a good idea. Overall, you should avoid having two things modify the DOM, since it creates hard to maintain code and instability (It's hard to tell what is modifying what!). I think you can achieve what you're trying to do with an onClick
event and conditional classes. Something like:
import React, { useState } from "react";
const App = () => {
const [active, setActive] = useState(false);
return (
<div className="box">
<div className={`.MuiFormControlLabel-root ${active ? "active" : ""}`}>
I am some div
</div>
<button onClick={() => setActive(!active)}>Click here!</button>
</div>
);
};
Here is a codepen if you want to see it in action: https://codepen.io/Chanodev/pen/gOjmgwa
But, if you want to go the jquery route, the best idea is to get some part of the DOM that is not manipulated by React, as demonstrated in https://reactjs.org/docs/integrating-with-other-libraries.html#how-to-approach-the-problem.
import React, {useEffect, useRef} from "react"
const App = () => {
const el = useRef(null)
useEffect(() => {
//Do stuff with 'el' HTMLElement here. You could also call the
// proposed code here, but manipulating DOM with
// both React and Jquery is a bad idea.
/*$(".PrivateSwitchBase-input-6").on('click', function(sss){
$(".MuiFormControlLabel-root").removeClass("active");
$(this).parents('.MuiFormControlLabel-root').addClass("active");
}); */
return () => {
//Cleanup stuff with 'el'. Destroy jquery listeners.
}
}, [])
return(
<div ref={el}>Hello</div>
);
}
A few good links:
Upvotes: 2