Home > Software engineering >  Pushing multiple Images to an Array In React - I am not getting the images inside images array
Pushing multiple Images to an Array In React - I am not getting the images inside images array

Time:03-08

I am getting trying to push images to an array whenever there is an onChange event but it is not happening. Can someone suggest why?

    
    const [images, setImages] = useState([]);
    const [newImages, setNewImages] = useState([]);
    const imageHandler = (e) => {
          setNewImages(e.target.files[0])
          setImages([...images, newImages])
          console.log(images)
    }  
    const onSubmit = (event) => {
        event.preventDefault();
        const form data = new FormData();
        formdata. append('files', images)
            axios.post("",
           formdata,
           options
        ).then((response) => {
          alert("Form Submitted");
        })
      }
     
    <td><input type="file" name='Files' onChange={imageHandler} required/></td>

CodePudding user response:

Some issues with your code:

  1. console.log(images) right after setImages(...) will not give the correct state value since react updates are not immediate. If you want to see values updating, you can add a useEffect hook
  2. You don't need to use another array to hold newImages, simply append to the images array

With these small fixes you can see a working demo:

const { useState, useEffect } = React;

const ImgUploader = () => {
  const [images, setImages] = useState([]);
  const imageHandler = (e) => {
    setImages([...images, e.target.files[0]]);    
  };
  
  // This is called after values are updated
  useEffect(() => {
    console.clear();
    images.length && console.log(images);
  }, [images]);
  
  const onSubmit = (event) => {
    event.preventDefault();
    console.log("Images:", images);
    const formdata = new FormData();
    formdata.append("files", images);
    
    // Do more operations here
    
  };

  return (
    <form onSubmit={onSubmit}>
      <input type="file" name="Files" onChange={imageHandler} required />
      <br />
      <br />
      <input type="submit" name="Submit" />
    </form>
  );
};

ReactDOM.render(<ImgUploader />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

  • Related