Search code examples
reactjsaws-amplify

How to turn this class using hooks


I am working on a project using aws-amplify and I ran across the docs for amplify to take the users file and display it. I attempted to change this into a functional component and use hooks but I am at a loss. Code below thanks for any advice and help.

class ImageViewer extends Component {
  handleUpload(event) {
    const file = event.target.files[0];
    const path = file.name;
    Storage.put(path, file).then(() => this.setState({ path }));
  }

  render() {
    return (
      <div className="rounded-circle user-profile-img shadow p-3 mb-5 bg-white rounded">
        <div>
          {this.state && <S3Image path={this.state.path} />}
        </div>
        <input type="file" onChange={this.handleUpload.bind(this)} />
      </div>
    );
  }
}

Solution

  • const ImageViewer = () => {
      const [path, setPath] = React.useState('');
    
      const handleUpload = (event) => {
        const file = event.target.files[0];
        const path = file.name;
        Storage.put(path, file)
          .then(() => setPath(path));
      }
    
        return (
          <div className="rounded-circle user-profile-img shadow p-3 mb-5 bg-white rounded">
            <div>
              {path && <S3Image path={path} />}
            </div>
            <input type="file" onChange={handleUpload} />
          </div>
        );
    }