Home > OS >  How to define react compoent like Foo and Foo.Bar by TypeScript
How to define react compoent like Foo and Foo.Bar by TypeScript

Time:06-09

I've already defined a react component by typescript, and I want to export it as a object so that I can add a new component on it.

interface IFooProps {
  title:string
}

interface IBarProps {
  content:string
}

const Foo:React.FC<IFooProps> = ({title}) => {
  return <div>{title}</div>
}

const Bar:React.FC<IBarProps> = ({content}) => {
  return <div>{content}<div>
}


// I want to add Bar componet as one of Foo's value, and export Foo component

Foo.Bar = Bar; // Type Error!!

export default Foo

I hope I can use it like this:

import Foo from './Foo'


const Content = () => {
  return (
    <>
      <Foo title="title"/>
      <Foo.Bar content=“content”/>
    </>
  )
}

However, when I add Bar component to Foo, I get a type error. How should I fix it?

CodePudding user response:

It would be something like this:

import React from 'react';

const Foo = ({ title }: { title: string }) => {
  return <div>{title}</div>;
};

const Bar = ({ content }: { content: string }) => {
  return <div>{content}</div>;
};

Foo.displayName = 'Foo';

export default Object.assign(Foo, {
  Bar: Bar,
});

CodePudding user response:

You just need to combine the <Bar/> component and its prop types to the <Foo/> components FC and props declaration. Like so:

interface IFooProps {
  title:string
}

interface IBarProps {
  content:string
}

const Foo:React.FC<IFooProps> & {Bar: React.FC<IBarProps>} = ({title}) => {
  return <div>{title}</div>
}

const Bar: React.FC<IBarProps> = ({content}) => {
  return <div>{content}</div>
}

Foo.Bar = Bar

If you are going to have a bunch of subcomponents then it may be easier to write out your own interface to combine with but I think you get the idea.

Using reacts FC declaration can get tricky and sometimes it is easier to just declare your props explicitly instead. But the above should work I think.

  • Related