I am trying to work on a project which is using a Layout/Template which uses a lot of jQuery.
I have learned to integrate the template with ReactJS Project, however
Is this approach correct? Is it the right way?
No. Don't use jQuery to attach event listeners to DOM elements created and managed by React. Use onClick'. I could not find
#sidebarCollapse` in your snippet. It could look something like this.
And the class for could dependent on this state
You'll notice, you hand over running operations like adding removing class, attributes and other DOM operations to React and simply declare how things must react to state changes. Amidst this, if you try to run jQuery operations, your UI could probably end up in an inconsistent state.
Migration could be done like this: replace parts of your UI elements with React. For eg, initially you could do,
And React side could look like this,
// main.js
ReactDOM.render( , document.getElementById('reactManagedNavBar'))
// MyNavBar.js could have the react components
This way you can incrementally migrate to React and still have jQuery side by side. Just dont manipulate the each other DOM elements.
Sometimes you need a jQuery plugins (animations, visualisations charts etc) inside a React component. Use refs!
class MyJQueryDependingComp extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
componentDidMount() {
// this.myRef.current is the dom element. Pass it to jQuery
}
render() {
return (
{/* rest of React elements */}
{/* rest of React elements */}
);
}
}
Again, refrain from touching your jQuery's DOM in React and vice versa.