H
H
HealSpirit2021-03-13 12:00:21
typescript
HealSpirit, 2021-03-13 12:00:21

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


index.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 - работает


https://codesandbox.io/s/modest-hooks-pksku

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-03-13
@bingo347

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 question

Ask a Question

731 491 924 answers to any question