Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
141
rated 0 times [  147] [ 6]  / answers: 1 / hits: 104386  / 7 Years ago, thu, april 6, 2017, 12:00:00

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

More From » reactjs

 Answers
11

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

[#58245] Tuesday, April 4, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaelynncherokeeg

Total Points: 697
Total Questions: 109
Total Answers: 104

Location: France
Member since Thu, Mar 18, 2021
3 Years ago
;