Search code examples
reactjstypescript

React functional component static property


I had a class component with another class component as his static property. Now I switched to a function component and I don't know how to keep the static property.

class Panel extends React.Component<Props> {
  public static Fieldset = PanelFieldset;
}

class PanelFieldset extends React.Component<Props> {
  ...
}

class App extends React.Component<Props> {
  public render() {
    return (
      <Panel>
        <Panel.Fieldset>
          ...
        </Panel.Fieldset>
      </Panel>
    )
  }
}

Now, switching to function component:

const Panel: React.FunctionComponent<Props> = (props) => {
  Panel.Fieldset = PanelFieldset;
}

but I get the error: Property 'Fieldset' does not exist on type 'FunctionComponent'.ts(2339)

Any help?


Solution

  • With implicit typing (Best Solution)

    The following shows an approach where you don't have to type your static properties explicitly. I personally prefer this over any other solution, since it is the shortest and most clean way.

    const PanelComponent: React.FC<Props> = (props) => {
     ...
    }
    
    export const Panel = Object.assign(PanelComponent, { PanelFieldset })
    

    With explicit typing (Previous Solution)

    If you want to type your static properties explicitly, extending @Andrew's answer, using typeof PanelFieldset should be more convenient to type your component.

    type IPanel<P> = React.FunctionComponent<P> & {
      Fieldset: typeof PanelFieldset; // add this
    }
    
    const Panel: IPanel<Props> = (props) => {
    }
    
    Panel.Fieldset = PanelFieldset;
    

    Source: https://github.com/react-bootstrap/react-bootstrap/blob/master/src/Dropdown.tsx#L230-L237