jayko03
jayko03

Reputation: 2481

Why is my type null in React and TypeScript?

I have a function based Child component.

interface ChildProps {
  files: File
}
const Child:React.FC<ChildProps> = ({files}) => {
  const [file, setFile] = React.useState(files);
  const emptyFile = new File([""], " ");
  React.useEffect(() => {
    if(files !== null || files !== undefined){
      setFile(files)
    }
    else{
      setFile(emptyFile)
    }
  })
  return (
    <div>
      {file!.name}
    </div>
  )
};

I get TypeError: Cannot read property 'name' of null error on {file!.name}. But I think it should be emptyFile at least, not null.
So my questions here,
1. why is it null? I think I take care of null case with if statement
2. How can I fix this?

Thanks in advance

Upvotes: 0

Views: 338

Answers (1)

Wojciech Dynus
Wojciech Dynus

Reputation: 922

According to the ChildProps interface you are supposed to be getting only valid files here. On the other hand you are trying to check if the files property from the parent is valid. So you are most likely passing some null from the parent. A first error is your condition for checking the files: if(files !== null || files !== undefined) {} If your files is null then you get a false in first statement, but it's not undefined, so the condition is true. You should try something like this:

interface ChildProps {
  files: File
}

const Child:React.FC<ChildProps> = ({files}) => {
  const [file, setFile] = React.useState(files);
  const emptyFile = new File([""], " ");

  React.useEffect(() => {
    if(!!files){
      setFile(files)
    }
    else{
      setFile(emptyFile)
    }
  }, [files]);

  return (
    <div>
      {file!.name}
    </div>
  )
};

Though the best option would be to just display the files and not to rewrite the prop into your local state. So you can try something like this:

interface ChildProps {
  files: File
}
const Child:React.FC<ChildProps> = ({files}) => {

  return (
    <div>
      {files ? files.name : ""}
    </div>
  )
};

Upvotes: 1

Related Questions