StrikeAgainst
StrikeAgainst

Reputation: 634

How to define an instantiated React component in a Typescript interface?

First of, I'm new to both React JS and Typescript. But basically I have a function which takes an object by interface:

interface ModalContents {
    component: React.Component,
    ...
}

export default function buildModal(contents : ModalContents){
    ...
    render() {
       return (
           <Modal>
               <ModalHeader>
                   ...
               </ModalHeader>
               <ModalBody>{contents.component}</ModalBody>
               <ModalFooter>
                   ...
               </ModalFooter>
           </Modal>
       );
    }
    ...
}

The interface is among others expecting an instantiated component which is to be inserted inside the render method. Now I'm using the function like this:

class ExampleModal extends React.Component<Props, State> {
    constructor(props) {
        super(props);
        ...
    }
  render() {
    return (
        <Container id="example-modal">
            ...
        </Container>
    );
  }
}

export default buildModal({component: <ExampleModal ... />, ...});

But for the component part of the object I pass to buildModal I am getting this error by VSC:

Type 'Element' is not assignable to type 'Component<{}, {}, any>'.

My goal is to get a rendered result like this:

<Modal> <ModalHeader> ... </ModalHeader> <ModalBody> <Container id="example-modal"> ... </Container></ModalBody> <ModalFooter> ... </ModalFooter> </Modal>

I'm aware that I could just pass the ComponentClass for ExampleModal instead and instantiate it inside buildModal, but I think this would make it unnecessarily cumbersome to pass the Props and States to the component.

So how can I do this? What is the right class to use inside of the interface? Is it even possible, or did I get something wrong about the concept here?

Upvotes: 1

Views: 1596

Answers (1)

Estus Flask
Estus Flask

Reputation: 223318

ExampleModal is React component, <ExampleModal ... /> is React element.

Considering that buildModal should accept an element, it should be:

interface ModalContents {
    component: React.ReactElement,
    ...
}

Upvotes: 1

Related Questions