React applying JQuery code to an element inside a component

こ雲淡風輕ζ 提交于 2019-12-05 13:08:29

To add and import JQuery is the first part.

1) Using webpack the best way I saw was to add a plugin in your webpack.config.js:

var webpack = require('webpack');

module.exports = {
    plugins: [
        new webpack.ProvidePlugin({
            '$': 'jquery',
            'jQuery': 'jquery',
            'window.jQuery': 'jquery'
        })
    ]
};

All these different typos are here to make JQuery availability compatible with all kinds of modules. Of course you need to npm install jquery and your plugin (wysihtml5).

2) Or you could import it in your index.html: <script src="jquery-3.1.1.min.js"></script>

EDIT: 3) Using meteor I did meteor add jquery and that did the trick.

Then, second part is to use it in React.

To use a jquery plugin on an element you need it to be rendered first, that's why you need to put the code in componentDidMount (which is run after the first render). And I would advise you (based on my different search when I had to do the same thing as you but with bootstrapTable) to make the render part the most simple (by removing ) and to use ReactDOM.findDOMNode(this) as a selector for JQuery:

import React, { Component } from 'react'
import ReactDOM from 'react-dom'

export class MyTextEditor extends Component {

    componentDidMount() {
        $(ReactDOM.findDOMNode(this)).wysihtml5()
    }

    render() {
        return (
            <textarea className="textarea"></textarea>
        )
    }
}

EDIT: Or to use React's refs

import React, { Component } from 'react'

export class MyTextEditor extends Component {

    componentDidMount() {
        $(this.refs.textareaIWantToUse).wysihtml5()
    }

    render() {
        return (
            <div className="form-group">
                <textarea className="textarea" ref="textareaIWantToUse"></textarea>
            </div>
        )
    }
}

Try this:

import React, { Component } from 'react';
import $ from 'jquery'; 

export class MyTextEditor extends Component {

  componentDidMount() {
    $(".textarea").wysihtml5()
  }

  render() {
    return (
        <div className="form-group">
            <textarea className="textarea"></textarea>
        </div>
     )
  }
}

NOTE: Do not forget to add JQuery library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!