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}> ❯ </a> ); } }
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.
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.
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.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With