Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jQuery dependant plugins in create-react-app

I want to use bootstrap and other jQuery plugins (datepicker, carousel, ...) in my React app which uses create-react-app.

Here is how I import jQuery and bootstrap:

import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import $ from 'jquery';
window.jQuery = window.$ = $;
import 'bootstrap/dist/js/bootstrap.min';

And I get the following error:

./src/App.js
  Line 5:  Import in body of module; reorder to top  import/first

Search for the keywords to learn more about each error.

Note that I don't want to use react-bootstrap package.

like image 472
Sohrab Taee Avatar asked May 20 '17 16:05

Sohrab Taee


People also ask

Can I use jQuery plugin in React?

We can easily use React components as jQuery plugins. We can create Backbone views and Angular components.

How does jQuery plugin integrate with React functional component?

Our jQuery app initially creates the React component using a call to React. createElement and passing in the context of the jQuery app to the components constructor. The component can then store the reference (available via the props argument) in its state and use it to update key elements on the web page.


2 Answers

to avoid having to require, one can also create a separate file to load jquery, eg.

jquery-loader.js:

import $ from "jquery"

window.$ = $
window.jQuery = $

and then

import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import './jquery-loader';
import 'bootstrap';
import 'bootstrap-datepicker';
like image 149
licancabur Avatar answered Oct 17 '22 01:10

licancabur


In this case for using bootstrap or bootstrap-datepicker I needed to require it instead of importing it.

import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import $ from 'jquery';
window.jQuery = window.$ = $;
require('bootstrap');
require('bootstrap-datepicker');
like image 21
Sohrab Taee Avatar answered Oct 17 '22 00:10

Sohrab Taee