Emily Yeh
Emily Yeh

Reputation: 551

Call JS function from another file in React?

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>
        );
    } 
}

Upvotes: 53

Views: 107584

Answers (1)

KornholioBeavis
KornholioBeavis

Reputation: 2442

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); 
    }

Upvotes: 108

Related Questions