Home > Mobile >  Getting error when using function component in react
Getting error when using function component in react

Time:10-11

Hi can anyone tell me how can i convert these code in function component. currently i m using class component and its working perfectly.

i am using these code for file upload with class component and same code i want to use when i am edit option. and for edit i am using function component.

onUpload = (url) => {
  console.log('I have been clicked', url);
  this.setState({brokerLogoUrl:url})
}
render() {
  const callbacks = {upload: this.onUpload};
  return (
    <Grid className="CoomonT">
      <UploadComponent {...callbacks} />
    </grid>
  )
}

CodePudding user response:

If you just need to convert class to functional component. You can do this.

1.Create brokerLogoUrl state using useState in function component.

const [brokerLogoUrl, setBrokerLogoUrl] = useState('');

  1. Create the onUpload function
const onUpload = (url) => {
  console.log('I have been clicked', url);
  setBrokerLogoUrl(url);
}
  1. Remove the render method, render just need when you in class component. And send onUpload function as prop.
  return (
    <Grid className="CoomonT">
      <UploadComponent onUpload={onUpload} />
    </grid>
  )

CodePudding user response:

const MyFuncComp = () => {
  const onUpload = (url) => {
    console.log('I have been clicked', url);
    this.setState({brokerLogoUrl:url})
  }
  const callbacks = {upload: onUpload};
  return (<Grid className="CoomonT">
      <UploadComponent {...callbacks} />
    </Grid>);
}
  • Related