Call JS function from another file in React?

JavascriptReactjs

Javascript Problem Overview


I have a function in a separate JavaScript file that I would like to call in a React component - how can I achieve this?

I'm trying to create a slideshow, and in slideshow.js, I have this function that increases the current slide index, like so:

function plusSlides(n) {
    showSlides(slideIndex += n);
}

In Homepage.jsx, I have a "next" button that should call plusSlides from slideshow.js when it is clicked, like so:

class NextButton extends React.Component {
    constructor() {
        super();
        this.onClick = this.handleClick.bind(this);
    }

    handleClick (event) {
        script.plusSlides(1); // I don't know how to do this properly...
    }

    render() {
        return (
            <a className="next" onClick={this.onClick}>
                &#10095;
            </a>
        );
    } 
}

Javascript Solutions


Solution 1 - Javascript

You can export it, or am I missing your question

//slideshow.js
export const plusSlides = (n)=>{
    showSlides(slideIndex += n);
}

and import it where you need to

//Homepage.js
import {plusSlides} from './slideshow'

handleClick (event) {
        plusSlides(1); 
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEmily YehView Question on Stackoverflow
Solution 1 - JavascriptKornholioBeavisView Answer on Stackoverflow