How to set up Rails active storage on the front end React form?

Viewed 22

Im stuck in the part where in I can set up my front end for Image uploads.I have set up my backend correctly for uploading images via active storage.Following this article "https://medium.com/@aliceshulin66/active-storage-in-react-rails-fb24c73227ff".However im conused about the front end.I need to add image upload to the review component. heres my code


import { useState } from "react";
import { useParams } from "react-router-dom";
import { useContext } from "react";
import { Cont } from "../Cont";

// handleAddReviews={(review) => setReviews([...reviews, review])} 
function AddReviewForm({handleAddReviews}){
  const {user}=useContext(Cont);
    const params = useParams();
   const[img,setImg]=useState("");
   const[r,setR]=useState("");
   const [images, setImages]=useState([])

   
     
      function handleReviewSubmit(event) {
        event.preventDefault();

        const formData=new formData()
        formData.append('r',r)
        for (let i=0;i<images.length;i++){
          formData.append('images[]',images[i])

        }
        formData.append("user_id",parseInt(user))
        formData.append("restaurant_id",params.id)

        fetch(`/reviews`, {
          method:"POST",
          body:formData
        })
          .then((r) => r.json())
          .then(()=>{
           window.location.reload()
            
          }
          );
      }


 
      
    return  (
        <>
        <h1>Add review form</h1>
        <form onSubmit={handleReviewSubmit}>
          
          <div>
          <input  type="file" accept="image/*" multiple onChange={e=>setImages(newImage=> ({...newImage, images: e.target.files}))}/>
          {/* <input 
                    required
                    type="file" 
                    name="picture" 
                    accept="image/png, image/gif, image/jpeg"
                    id="picture"
                    // onChange={e => {setNewTrash(newTrash => ({...newTrash, picture: e.target.files[0]}))}}
                /> */}
          </div>

       <div>
        <label htmlFor="r"  >Review</label>
         <input type="text" name="r"   value={r}  onChange={(e) => setR(e.target.value)} placeholder="review" />
      </div>
       <input type="submit" />

        </form>
        </>
    )
}
export default AddReviewForm;

0 Answers
Related