0

I'm having a little problem adding external javaScript file to my React App. I tried so many things but none of them worked. The last thing I did is:

step#1 : creating JS file and create functions.

step#2 : import the functions form my js file.

step#3 : call the functions.

The issue is when I run: npm start, everything work fine. But when I run: nom build, the script won't work!

This is my js file that I created with exporting functions

            export function BackgroundMove() {
            $(document).ready(function() {
                let movementStrength = 25;
                let height = movementStrength / $(window).height();
                let width = movementStrength / $(window).width();
                $("body").mousemove(function(e){
                        let pageX = e.pageX - ($(window).width() / 2);
                        let pageY = e.pageY - ($(window).height() / 2);
                        let newvalueX = width * pageX * -1 - 25;
                        let newvalueY = height * pageY * -1 - 50;
                        $('body').css("background-position", newvalueX+"px     "+newvalueY+"px");
                });
                });
            }


            export function HeaderMove() {
                $(document).ready(function(){
                    $('#nav-icon0,#nav-icon1,#nav-icon2,#nav-icon3,#nav-icon4').click(function(){
                        $(this).toggleClass('open');
                    });
                });
            }

Here I'm importing my functions

    import {HeaderMove, BackgroundMove} from '../../style';

Calling the functions:

   componentDidMount() {
      HeaderMove();
      BackgroundMove();
    }

As I mentioned, this will work fine when I run

 npm start 

But, when I run

npm build

my script won't work

2
  • Why you don't add this script to index.html? Commented Dec 29, 2018 at 23:20
  • I tried, it didn't work Commented Dec 30, 2018 at 1:22

1 Answer 1

1

Please refer to the following code to import external javascript file inside component:

componentDidMount() {
   var script = document.createElement('script')
   script.src = // path of external javascript file.
   script.class = "external-script"
   document.body.appendChild(script);
}

and inside componentWillUnmount you can remove that file using the class name.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Piyush, I'm having a little problem understanding your code. script.class = "external-script". Is the "external-script" the name of the js file or the function?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.