Search code examples
reactjstwitter-bootstrap-3create-react-app

create-react-app how to use directly imported scripts in html


I am using bootstrap in my react app generated with create-react-app

Below are two imports that I am using in my index.html

<script src="./vendor/jquery-3.1.0.min.js"></script>
<script src="./vendor/bootstrap.min.js"></script>

However in code when I use something like

$('.dropdown').dropdown()

I get an error as - error '$' is not defined no-undef Can someone help me with this. Thanks!


Solution

  • If you need jQuery, run:

    npm install --save jquery
    

    Then you can use it in the app code:

    import $ from 'jquery';
    

    Note that this only works with versions 2.x and above.


    You can also use it as a script tag.
    This is not encouraged.

    To do it, put jQuery into the public folder and add this to HTML:

    <script src="%PUBLIC_URL%/jquery-3.1.0.min.js"></script>
    

    Then you can use it from the app:

    const $ = window.$;
    

    In general I would recommend trying React Bootstrap instead of Bootstrap in React projects. It provides similar looking components but doesn't need jQuery and works on top of React.

    I hope this helps! Please file issues if you're confused about something. We are happy to help.