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.