Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 139863

How to pass state to child component with function based React?

$
0
0

I try to pass uploaded file to the child component that both parent and child components are the function based.
I am using React, TypeScript and Material-UI


Parents

import React from 'react';
import Child from './Child';

const Parent:React.FC =() => {
  const [file, setFile] = React.useState(null);
  const onChangeFile = (e:any) => {
    setFile(e!.target.files[0]);
  }
  return(
    <div>
    <input
      accept="*.*"
      onChange={onChangeFile}
      id="uploadFile"
      type="file" />
    <Button
      onClick={() => document.getElementById('uploadFile')!.click()}
      component='span'>
      Upload file
    </Button>
    <Child files={file: File}>
    </div>

Child

import React from 'react';
const Child:React.FC = (props) => {
  return(
    <div>
      {{ props }}
    </div>
  )
}
export default Child

At this point, I just want to print out the file's information that I have {{ props }}. I am a newbie to React and please tell me anything I did wrong. Thanks in advance!
EDIT
I changed Child,

const Child:React.FC = ({files}) => {
  return(
    <div>
      { files }
    </div>
  )
}

then it throws error,

property 'files' does not exist on type '{children?:ReactNode; }'



EDIT2 Following to @EarlePoole, I changed my code.
Parents

const Parent:React.FC = () => {
 //...
 <Child file={file} />

Child

const Child:React.FC =(props) => {
  return(
  <div>
    {props.file.file}
  </div>
  )
}

In parent component, I got this error

Type '{ file: any; } is not assignable to type 'IntrinsicAttributes & {children ?:ReactNode; }'. Property 'file' does not exist on type 'IntrinsicAttributes & { children?: ReactNode}'

In Child component,

Property 'file' does not exist on type '{children?:ReactNode; }'

Viewing all articles
Browse latest Browse all 139863

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>