Kavoos
Kavoos

Reputation: 417

Calling a function by its name (string) in React.Component using TypeScript

I'm writing a React app with TypeScript. My component's state looks like this:

type UploadState = {
  ...
  modal: string | null
  ...
}

In my render I have:

render() {
  return <div>{this.renderModal()}</div>
}

somewhere in the code I have:

this.setState({ modal: 'mappingModal' })

and finally renderModel is:

renderModal = () => {
  if (this.state.modal === null) {
    return
  }
  return this[modal as keyof this]() //It doesn't work
}

I EXPECT to have the return value of mappingModal:

mappingModal = () => {
  return <h1>Some text or whatever!</h1>
}

But I get this error because of () in this[modal as keyof this]() :

Cannot invoke an expression whose type lacks a call signature.
Type '{}' has no compatible call signatures.ts(2349)

And if I remove () I get this error in the browser:

Warning: Functions are not valid as a React child.
This may happen if you return a Component instead of <Component /> from render.
Or maybe you meant to call this function rather than return it.

Any solution?

UPDATE (POTENTIAL ANSWER)

It seems if I use this[modal as keyof Upload]() - and Upload is my component name of course - I'll not have any problem. Hopefully it'll not cause any future bug

Upvotes: 3

Views: 3344

Answers (1)

Kavoos
Kavoos

Reputation: 417

It seems if I use this[modal as keyof Upload]() - and Upload is my component name of course - I'll not have any problem. Like this:

class Upload extends React.Component<UploadProps, UploadState> {
  ...
  renderModal = () => {
    if (this.state.modal === null) {
      return
    }
    return this[modal as keyof Upload]()
  }
  ...
}

Upvotes: 1

Related Questions