Categories
React Answers

How to call JavaScript function from another file in React?

Spread the love

Sometimes, we want to call JavaScript function from another file in React.

In this article, we’ll look at how to call JavaScript function from another file in React.

How to call JavaScript function from another file in React?

To call JavaScript function from another file in React, we export the function we want to call and then import it.

For instance, we write

export const plusSlides = (n) => {
  showSlides((slideIndex += n));
};

in slideShow.js.

Then we write

import { plusSlides } from "./slideShow";

//...

const Comp = () => {
  //...
  const handleClick = (event) => {
    plusSlides(1);
  };
  //...
};

to import the plusSlides function from the slideShow.js file.

And then we call it in the handleClick function.

Conclusion

To call JavaScript function from another file in React, we export the function we want to call and then import it.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *