Answer the question
In order to leave comments, you need to log in
How to type React.memo if the functional component has static properties?
Hello. There is a functional component (React) with 2 static fields (string and object). I want to use them in different places. I ran into a problem with React.memo typing. If you access these fields in the component itself (App.tsx), then everything works. But in index.tsx, when accessing these fields when exporting without memo, it works, but when exporting with memo, it does not work. How to type memo in this case?
App.tsx
import { FC, memo } from "react";
interface IAppProps {
title: string;
}
interface IStatic<T> {
someStaticString: string;
someStaticObj: T;
}
const someObj = {
SOME_KEY: "SOME_VALUE"
};
const App: FC<IAppProps> & IStatic<typeof someObj> = (props) => {
const { title } = props;
return <>{title}</>;
};
App.someStaticString = "someStaticString";
App.someStaticObj = someObj;
console.log(App.someStaticObj); // В App.tsx это обращение работает
export default memo(App); // не сработает обращение к статике в index.tsx
// export default App; // без memo работает и в index.tsx и App.tsx
import { render } from "react-dom";
import App from "./App";
const rootElement = document.getElementById("root");
render(<App title={"some title"} />, rootElement);
console.log(App.someStaticObj); // При exporte с memo не работает, без memo - работает
Answer the question
In order to leave comments, you need to log in
As far as I know (I'm not a React expert, I could be wrong), memo will not forward static properties. It essentially creates a new HOC around your component. And static properties need to be hung on this wrapper:
import { FC, memo } from "react";
interface IAppProps {
title: string;
}
interface IStatic<T> {
someStaticString: string;
someStaticObj: T;
}
const someObj = {
SOME_KEY: "SOME_VALUE"
};
const App: FC<IAppProps> & IStatic<typeof someObj> = memo((props) => {
const { title } = props;
return <>{title}</>;
});
App.someStaticString = "someStaticString";
App.someStaticObj = someObj;
export default App;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question