React Js Rearrange Image Position | change order of img element | reorder
React Js Rearrange Image Position | change order of img element | reorder:React JS allows developers to dynamically rearrange the position and order of image elements within a component. By using state and manipulating the order in which images are rendered, developers can easily change the visual layout of images on the page. This flexibility allows for interactive and responsive designs where images can be reordered based on user interactions or other conditions




Thanks for your feedback!
Your contributions will help us to improve service.
How can I rearrange the positions of images dynamically in a Reactjs?
This ReactJS code creates an image gallery that allows users to rearrange images by dragging and dropping them. It defines an App
component that uses React's useState
hook to manage the state of the images array. Each image is represented as an object with a url
. The startDrag
, onDragOver
, and onDrop
functions enable drag-and-drop functionality. When an image is dropped in a new position, the array is updated to reflect the new order. The images are displayed in a container, and the user can drag images to change their positions.
React Js Rearrange Image Position Example
<script type="text/babel">
const { useState } = React;
// Define the App component
const App = () => {
const [images, setImages] = useState([
{
url: "https://www.sarkarinaukriexams.com/images/import/sne4446407201.png",
},
{
url: "https://www.sarkarinaukriexams.com/images/import/sne86811832.png",
},
// Add more images here
]);
const [isDragging, setIsDragging] = useState(false);
const [dragIndex, setDragIndex] = useState(-1);
const [dragOffset, setDragOffset] = useState(0);
const startDrag = (index, event) => {
setDragIndex(index);
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.setData("text", index);
};
const onDragOver = (event) => {
event.preventDefault();
event.dataTransfer.dropEffect = "move";
};
const onDrop = (index, event) => {
event.preventDefault();
const movedImageIndex = event.dataTransfer.getData("text");
if (movedImageIndex !== "") {
const fromIndex = parseInt(movedImageIndex);
const toIndex = index;
// Rearrange the images array
const movedImage = images[fromIndex];
const updatedImages = [...images];
updatedImages.splice(fromIndex, 1);
updatedImages.splice(toIndex, 0, movedImage);
setImages(updatedImages);
}
setDragIndex(-1);
};
return (
<div className="container">
<h3>Reactjs Rearrange Image Position</h3>
<div className="image-container">
{images.map((image, index) => (
<div
key={index}
draggable="true"
onDragStart={(event) => startDrag(index, event)}
onDragOver={(event) => onDragOver(event)}
onDrop={(event) => onDrop(index, event)}
>
<img src={image.url} alt="Image" />
</div>
))}
</div>
</div>
);
};
ReactDOM.render(<App />, document.getElementById("app"));
</script>