Cardoso
Cardoso

Reputation: 1088

react typescript component set prop with condition

I'd like to set the component's prop when the variable's value defined. Below is my current code.

import Cropper from 'react-easy-crop'
...
interface State {
 ...
  coverFile: File | null;
  ...
}
class Test extends React.PureComponent<Props, State> {
  state = {
    ...
    coverFile: null,
    ...
  };
...
const file = event.target.files;
self.setState({
              coverFile: file[0],
            });

<Cropper
  image={coverFile?coverFile:undefined}
  ...
/>

And this is the error message.

No overload matches this call.
  Overload 1 of 2, '(props: Readonly<CropperProps>): Cropper', gave the following error.
    Type 'null | undefined' is not assignable to type 'string | undefined'.
      Type 'null' is not assignable to type 'string | undefined'.
  Overload 2 of 2, '(props: CropperProps, context?: any): Cropper', gave the following error.
    Type 'null | undefined' is not assignable to type 'string | undefined'.ts(2769)

How can I solve this problem?

Upvotes: 1

Views: 336

Answers (3)

StormyTalent
StormyTalent

Reputation: 227

The image props for Cropper stands for string. And it seems to be an error with the code as following that you mentioned.

<Cropper
  image={coverFile?coverFile:undefined}
  ...
/>
It would be fine by replacing it by
  <Cropper
    image={coverFile || undefined}
    ...
  />
or
  {
  image ?
  <Cropper
    image=coverFile
    ...
  /> : ''
  }

Hope your success

Upvotes: 0

Sohaib
Sohaib

Reputation: 11297

This explains your error message

Type 'null | undefined' is not assignable to type 'string | undefined'.

Cropper's image prop expects a string or undefined but you are passing null or undefined

Did you initialise coverFile as null? If so, you can set it to undefined to silence the error

Update: If you can't figure out where the null is coming from you can simply do this:

<Cropper
  image={coverFile || undefined}
  ...
/>

Upvotes: 3

marzzy
marzzy

Reputation: 788

First, you don't need to use (JSX attribute) image?: string | undefined you can write image?: string because, with strict null checks, an optional parameter automatically adds | undefined

Second, based on react-easy-crop document it needs to image or video (at least one of them) to be required, so if there was an undefined image, you need to pass a valid video parameters I think this could help :

 {coverFile && (
  <Cropper
   image={coverFile}
   ...
 />)
 }
 

Upvotes: 0

Related Questions