Reputation: 167
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>
);
}
Upvotes: 3
Views: 23713
Reputation: 717
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.
Upvotes: 10