53

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>
        );
    } 
}
rdonatoiop
  • 1,185
  • 1
  • 14
  • 28
Emily Yeh
  • 551
  • 1
  • 4
  • 9

1 Answers1

108

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); 
    }
KornholioBeavis
  • 2,402
  • 2
  • 19
  • 26