ReactJS with jQuery
suggest changeFirst, import the jQuery library. Also import findDOMNode, because this example manipulates the DOM, and import React. Direct DOM edits bypass React’s render, so keep them limited.
import React from 'react';
import { findDOMNode } from 'react-dom';
import $ from 'jquery';
handleToggle runs when an icon is clicked. It shows or hides the node referenced as toggle.
handleToggle = () => {
const el = findDOMNode(this.refs.toggle);
$(el).slideToggle();
};
Set the ref named toggle:
<ul className="profile-info additional-profile-info-list" ref="toggle">
<li>
<span className="info-email">Office Email</span> me@shuvohabib.com
</li>
</ul>
The element that calls handleToggle from onClick:
<div className="ellipsis-click" onClick={this.handleToggle}>
<i className="fa-ellipsis-h"/>
</div>
The full component looks like this. Class fields such as handleToggle = () => {} need the class-properties transform; they are not ES6.
import React from 'react';
import { findDOMNode } from 'react-dom';
import $ from 'jquery';
export default class FullDesc extends React.Component {
constructor() {
super();
}
handleToggle = () => {
const el = findDOMNode(this.refs.toggle);
$(el).slideToggle();
};
render() {
return (
<div className="long-desc">
<ul className="profile-info">
<li>
<span className="info-title">User Name : </span> Shuvo Habib
</li>
</ul>
<ul className="profile-info additional-profile-info-list" ref="toggle">
<li>
<span className="info-email">Office Email</span> me@shuvohabib.com
</li>
</ul>
<div className="ellipsis-click" onClick={this.handleToggle}>
<i className="fa-ellipsis-h"/>
</div>
</div>
);
}
}
That is one way to use jQuery in a React component. Prefer React state for showing and hiding when you do not need a jQuery animation.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents