When I remove the setState
(in this case setImgDrag), the state does not take the value of the img selected, basically what I do is get the img from the sidebar and when the onDragStart
event is fired I take the scr of the img and store it in a var called imgDrag, that works perfect, the point is that when I try to set the state of the img that is in the div, the state "imgDrag" does not get set. If you have a better implementation I will accept it.
import Img from "./img-card"
const DropImg=()=>{
const [img,setImg]=useState([])
const[imgDrag,setImgDrag]=useState()
const[position,setPosition]=useState({x:0,y:0})
let imgSelected;
let getImg=(e)=>{
let img=e.target.files
for(let i=0;i<img.length;i++){
setImg((prevState)=>{return ( img? [...prevState,URL.createObjectURL(img[i])] : [...prevState]) })
}
}
let dragOver=(e)=>{
e.preventDefault()
let xPosition=e.clientX
let yPosition=e.clientY
setPosition(()=>{return {["x"]:xPosition,["y"]:yPosition}})
console.log(position)
}
let drop=(e)=>{
e.preventDefault();
setImgDrag(imgSelected)
console.log(imgDrag)
}
return (
<div className="flex bg-gray-400">
<div className=" bg-gray-800 w-1/4 rem-width-25 px-5 pt-6 h-screen">
<div className="block">
<div className="relative bg-teal-500 border rounded py-12 m-auto text-center w-11/12 text-white ">
<input type="file" id="img" className="absolute top-0 m-auto left-0 cursor-pointer bg-gray-200 border border-gray-300 mb-3 outline-none py-10 px-5 rounded shadow-sm opacity-0" multiple onChange={getImg} />
Click Here Or Drop An Image
</div>
</div>
<div className="grid w-full grid-cols-3 gap-2 mt-10">
{(img? img.map((src,index)=>{return <Img key={index} id={index} draggable="true" onDragStart={e=>{ imgSelected= e.target.src}} src={src}/>}):null)}
</div>
</div>
<div onDrop={drop} onDragOver={dragOver} className="w-9/12 h-screen">
{imgDrag? <Img src={imgDrag} style={{width:400}}/>: null}
{img? null:<p id="drop-here" className="text-center">Drop Image Here!</p>}
</div>
</div>)
}
export default DropImg