What is the correct way to include jquery libraries including CSS when using create-react-app?

144 views Asked by At

I'm trying to utilize a jquery library called select2 in my React app created by create-react-app.

I have added jquery and select2 to my package.json and I can make the javascript work.

However, the styling does not work as the css file of select 2 is not included correctly.

I can see the following file inside my project:

node_modules/select2/dist/css/select2.min.css

and of course I can copy the file into public/css and add this to my index.html:

<link href="css/select2.min.css" rel="stylesheet">

I'm sure there is a better way utilizing the power of webpack and the create-react-app toolchain. But how?

2

There are 2 answers

1
bitten On

I often just require the css in the index of my app.

index.js: require('node_modules/select2/dist/css/select2.min.css')

0
resnbl On

I think a better way is to "import" the CSS into the .js file that references your jquery library:

import 'select2/dist/css/select2.min.css';

That way, the CSS will be included in the bundle.js file that is generated, and you have "localized" this dependency to the code that requires it.

On a related note: you may wish to Google "react select" and explore the many libraries that provide a more "React-ish" way of implementing a widget.