Saturday, 25 September 2021

React: Click button to load image from static location in directory

When the user clicks "Sample 1" button on the screen, it should load and display an image located locally.

Here is what I tried but it does not work

import React, {Component} from 'react';
import image_1 from "../../static_media/1.png"
import image_2 from "../../static_media/2.png"
import {Container, Image} from "react-bootstrap";


class Classifier extends Component {
    state = {
        files: [],
        isLoading: false,
        recentImage: null,
    }


    handleClick = (e) => {

        const ImageData = [image_1, image_2]

        const FILES = {
            "image_1": [{
                name: "image_1",
                size: "100",
                image: ImageData[0]
            }],
            "image_2": [{
                name: "image_2",
                size: "200",
                image: ImageData[1]
            }],
            "image_3": [{
                name: "image_3",
                size: "300",
                image: ImageData[1]
            }],
        }

        // you can now use this value to load your images
        const prefix = e.target.dataset.prefix; // 1
        this.setState({
            files: [],
            isLoading: true,
            recentImage: null
        })
        this.loadImage(FILES[`image_${prefix}`])
    }

    loadImage = (files) => {
        setTimeout(() => {
            this.setState({
                files,
                isLoading: false
            }, () => {
                console.log(this.state.files[0])
            })
        }, 1000);
    }

    render() {
        const files = this.state.files.map(file => (
            <li key={file.name}>
                {file.name} - {file.size} bytes
            </li>
        ));
        return (

            <Container>

                <button
                    data-prefix="1"
                    onClick={(e) => this.handleClick(e)}
                    className="btn btn-primary">
                    Sample 1
                </button>
                <aside>
                    {files}
                </aside>

                <div className="img-fluid">
                    {this.state.files.length > 0 &&
                    <Image
                        src={URL.createObjectURL(this.state.files[0])}
                        height='400' rounded/>
                    }
                </div>
            </Container>


        )
    }
}

export default Classifier;

I get an error

TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed.

78 | 79 | {this.state.files.length

0 && 80 | <Image 81 | src={URL.createObjectURL(this.state.files[0])} | ^ 82 | height='400' rounded/> 83 | } 84 |

Ideally, I would like to create an actual image object so I am able to send this image to the Django REST API.



from React: Click button to load image from static location in directory

No comments:

Post a Comment