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

1 Answer 1

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); 
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much for your help! I figured out what I was doing wrong, and now it works perfectly! :^)
can you explain it in react Hook?
pretty much exactly the same thing, except you wouldnt call it inside a class function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.