-
Notifications
You must be signed in to change notification settings - Fork 0
/
dragNdrop.jsx
86 lines (75 loc) · 2.35 KB
/
dragNdrop.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import React, { useEffect, useRef, useState } from "react";
function App() {
const [inputs, setInputs] = useState([]);
const [isDragging, setIsDragging] = useState(false);
const dragIndex = useRef();
const dragOverIndex = useRef();
useEffect(() => {
const storedInputs = JSON.parse(localStorage.getItem("inputs"));
if (storedInputs && storedInputs.length > 0) {
setInputs(storedInputs);
} else {
// Setting up initial inputs
setInputs(["", "", "", "", "", "", ""]);
}
}, []);
const handleClear = () => {
localStorage.removeItem("inputs");
window.location.reload();
};
const handleInputChange = (index, value) => {
const inputsClone = [...inputs];
inputsClone[index] = value;
setInputs(inputsClone);
localStorage.setItem("inputs", JSON.stringify(inputsClone));
};
const handleDragStart = (index) => {
setIsDragging(true);
dragIndex.current = index;
};
const handleDragEnter = (index) => {
if (isDragging) {
dragOverIndex.current = index;
}
};
const handleDragEnd = () => {
setIsDragging(false);
const inputsClone = [...inputs];
const draggedInput = inputsClone[dragIndex.current];
inputsClone.splice(dragIndex.current, 1);
inputsClone.splice(dragOverIndex.current, 0, draggedInput);
setInputs(inputsClone);
localStorage.setItem("inputs", JSON.stringify(inputsClone));
};
return (
<>
<div style={{ textAlign: "center" }}>
<h1> Drag & Drop Fields</h1>
<div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
{inputs.map((input, index) => (
<input
key={index}
type="text"
value={input}
onChange={(e) => handleInputChange(index, e.target.value)}
draggable
onDragStart={() => handleDragStart(index)}
onDragEnter={() => handleDragEnter(index)}
onDragEnd={handleDragEnd}
onDragOver={(e) => e.preventDefault()}
style={{
padding: "5px",
margin: "5px",
backgroundColor: "#eee",
cursor: "pointer",
width: "200px",
}}
/>
))}
</div>
</div>
<button onClick={handleClear}>Clear</button>
</>
);
}
export default App;