Moody
Moody

Reputation: 43

Display an image in avatar React

i want to display uploaded image inside the avatar so i wrote this code:

export default function App() {
  const handleChange = function loadFile(event){
    document.getElementById("avatar").src = URL.createObjectURL(event.target.files[0]);
  }
  return (
    <div className="App">
      <input type="file" onChange={handleChange} id="upload" accept="image/*"  style={{display:"none"}}/>
      <label htmlFor="upload">
        <IconButton color="primary" aria-label="upload picture" component="span">
        <Avatar  id="avatar"  src="/*photo URL using GetEvent */" 
              style={{

                        width: "60px",
                        height: "60px",
                     }}
    />
    </IconButton>
    </label>
    <label fro="avatar"></label>
    </div>
  );
}

But unfortunately, the code run with and doesn't display the image! I tried to figure out where is my mistake but i didn't found it.

Upvotes: 0

Views: 3729

Answers (1)

Khabir
Khabir

Reputation: 5862

Hi, I have fixed your code. please check it.

export default function App() {
    const [file, setFile] = useState(null);

    const handleChange = function loadFile(event) {
        if (event.target.files.length > 0) {
            const file = URL.createObjectURL(event.target.files[0]);
            setFile(file);
        }
    };
    return (
        <div className="App">
            <input type="file" onChange={handleChange} id="upload" accept="image/*" style={{display: "none"}}/>
            <label htmlFor="upload">
                <IconButton color="primary" aria-label="upload picture" component="span">
                    <Avatar id="avatar" src={file}
                            style={{

                                width: "60px",
                                height: "60px",
                            }}
                    />
                </IconButton>
            </label>
            <label htmlFor="avatar"/>
        </div>
    );
}

Upvotes: 3

Related Questions