Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>         );     }  } 
like image 673
Emily Yeh Avatar asked Apr 06 '17 18:04

Emily Yeh


People also ask

Can we call function from another component React?

You separate all events into separated state and actions, and dispatch them from components. if you need to use function from the child in a parent component, you can wrap in a third component, and clone parent with augmented props.

How do I export and import functions in React?

Use named exports to export multiple functions in React, e.g. export function A() {} and export function B() {} . The exported functions can be imported by using a named import as import {A, B} from './another-file' . You can have as many named exports as necessary in a single file.

How do you import js file in React?

Installation: Open a terminal inside your ReactJS project folder and write the following code to install react-script-tag Package. Import 'ScriptTag' component: Import the built-in 'ScriptTag' component from the react-script-tag library at the top of the file where we want to add the script tag.

What is && operator in React?

Inline If with Logical && Operator It works because in JavaScript, true && expression always evaluates to expression , and false && expression always evaluates to false . Therefore, if the condition is true , the element right after && will appear in the output. If it is false , React will ignore and skip it.


1 Answers

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);      } 
like image 107
KornholioBeavis Avatar answered Sep 21 '22 18:09

KornholioBeavis