Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export function inside functional component in react

It is possible to export a function that is inside a functional component and that can be imported into another? Example code: https://codesandbox.io/s/blissful-sanne-chk5g?file=/src/App.js:0-275

Component One:

import React from 'react'

const componentOne = () => {

    function hello(){
    console.log("Hello, says the componentOne")
  }
  return (
    <div>
      
    </div>
  )
}

export default componentOne

Component Two:

import React from 'react'
import {hello} from "./ComponentOne"

const componentTwo = () => {

   
  return (
    <div>
      
    <button
    onClick={hello}>
        Hello
    </button>

    </div>
  )
}

export default componentTwo

App.js

import ComponentTwo from "./components/ComponentTwo";
import "./styles.css";

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <ComponentTwo />
    </div>
  );
}
like image 840
JGPcode Avatar asked Oct 23 '25 18:10

JGPcode


1 Answers

Exporting a function from a functional component in order to be used by a parent component is possible.

All you have to do is to make good use of refs.

see the below example:

Component One

import React, { forwardRef, useImperativeHandle } from "react";

const ComponentOne = forwardRef((props, ref) => {
    useImperativeHandle(ref, () => ({
        hello() {
            console.log("Hello, says the componentOne");
        }
    }));

    return (
        <div></div>
    );
});

export default ComponentOne;

Component Two

import React { useRef } from "react";
import ComponentOne from "./ComponentOne";

const ComponentTwo = () => {
    const componentOneRef = useRef(null);
    const componentOne = <ComponentOne ref={ componentOneRef } />;
   
    return (
        <div>
            <button onClick={ () => componentOneRef.current.hello() }>Hello</button>
        </div>
    );
}

export default componentTwo;

Let me add that in your example it seems you do not want to render your ComponentOne but only use the hello function inside of it. If this is the case, probably a functional component is not what you are really looking for: you may think of creating a utility javascript file where you export functions.

like image 68
ThomasSquall Avatar answered Oct 26 '25 08:10

ThomasSquall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!