I have a function getFontColor(), that I would like to extract to a utils folder, and call it in a component. This function though, uses a function that is inside my component (getBgColor()). How do I pass getBgColor to the util function and how to I call the util function in my component?
Util function I want to extract:
export const getFontColor = () => {
const bgColor = getBgColor();
return something;
};
Function getBgColor() which is inside the component:
const getBgColor = () => {
return something
};
Calling the util function:
<StyledTitle color={getFontColor}>
{node.label}
</StyledTitle>
How can I communicate those? The main issue, is how do I pass the getBgColor to the external function?
CodePudding user response:
Just pass your getBgColor
-function to your utils-function. In Javascript functions are first class objects, so they behave like any other object, such as an int or a list. That means that you can use functions as arguments to other functions.
// utils.js
export const getFontColor = async (props) => {
const fontColor = await getFontColorAsync(props);
return fontColor;
}
const getFontColorAsync = async ({ getBgColor }) => {
const bgColor = getBgColor();
return something;
}
//component.jsx
import { getFontColor } from "./utils.js"
function Component() {
const getBgColor = () => {
return something;
};
const fontColor = getFontColor({ getBgColor });
return (
<StyledTitle color={fontColor}>
{node.label}
</StyledTitle>
);
}
CodePudding user response:
The best and easiest way is just to call that function
<StyledTitle color={getFontColor()}>
{node.label}
</StyledTitle>
Especially because props color
is expecting color, but not a function to call it later.