0

I have a simple list where in each element there is an input to choose an image to upload. The choosen image is displaying correctly, but I can't manage to choose different images for different elements.

My list seems to render the same value for all items. My issue is that any image will be present in all elements. I want a different image for each element.

This is what I tried so far :

  const handleChange = (index, newimage) => {
    const cloneList = [...list];
    cloneList[index].image = newimage;
    setList(cloneList);
  };

https://codesandbox.io/s/cool-sid-74le8?file=/src/App.js

import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";

export default () => {
  const initialList = [
    {
      id: "1",
      image: "https://picsum.photos/150/150.jpg"
    },
    {
      id: "2",
      image: " "
    },
    {
      id: "3",
      image: " "
    }
  ];

  const [list, setList] = React.useState(initialList);
  const [file, setFile] = useState(null);

  const handleFile = (event) => {
    setFile(URL.createObjectURL(event.target.files[0]));
  };

  /* What I tried to change a specific element

  const handleChange = (index, newimage) => {
    const cloneList = [...list];
    cloneList[index].image = newimage;
    setList(cloneList);
  };*/

  return (
    <div>
      <ul>
        <div>
          {list.map((item, index) => (
            <li key={item.id}>
              <span>
                <input type="file" onChange={handleFile} />
                <img
                  src={file}
                  alt=""
                  style={{ width: "100px", height: "100px" }}
                />
              </span>
            </li>
          ))}
        </div>
      </ul>
    </div>
  );
};
3

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.