search
HomeWeb Front-endCSS TutorialMake an Image drag and drop with CSS in React

Make an Image drag and drop with CSS in React

React is a popular JavaScript library for building user interfaces, and its flexibility and versatility make it a great choice for building interactive applications. In this tutorial, we will show you how to create a drag-and-drop feature for images using only CSS in React.

Step 1 —

To start, let's set up a React project. You can use either Create React App or any other setup method that works best for you. Let's make a React application using create-react-app.

npx create-react-app drag-and-drop

Step 2 —

Replace App.js and App.css with the below code.

App.js

import './App.css';

function App() {
  return (
    <div classname="App">
      <h2 id="Select-Image">Select Image:</h2>
      <div classname="image-area">

      </div>
    </div>
  );
}

export default App;

App.css

.App {
  text-align: center;
  width: 100vw;
  height: 100vh;

}

.heading {
  font-size: 32px;
  font-weight: 500;
}

Step 3 —

Now create a new file and component ImageContainer.js in the src directory and take a div for drag and drop container.

ImageContainer.js

import React from 'react';

const ImageContainer = () => {

    return (
        <div classname="image-container">

        </div>
    );
};

export default ImageContainer;

Then make a CSS file ImageContainer.css in the src directory and add some styles in the image container.

ImageContainer.css

.image-container {
    width: 60%;
    height: 90%;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 2px dashed rgba(0, 0, 0, .3);
}

Step 4 —

Now we will take a div with an input field and input text title inside the .image-container class and add some style in the ImageContainer.css file. We will also take a state for the image URL and an onChage function for the update state.

ImageContainer.js will be

import React from 'react';
import './ImageContainer.css';

const ImageContainer = () => {
    const [url, setUrl] = React.useState('');

    const onChange = (e) => {
        const files = e.target.files;
        files.length > 0 && setUrl(URL.createObjectURL(files[0]));
    };

    return (
        <div classname="image-container">
            <div classname="upload-container">
                <input type="file" classname="input-file" accept=".png, .jpg, .jpeg" onchange="{onChange}">
                <p>Drag & Drop here</p>
                <p>or</p>
                <p>Click</p>
            </div>
        </div>
    );
};

export default ImageContainer;

ImageContainer.css will be

.image-container {
    width: 60%;
    height: 90%;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 2px dashed rgba(0, 0, 0, .3);
}

.upload-container {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: white;
}

.upload-container>p {
    font-size: 18px;
    margin: 4px;
    font-weight: 500;
}

.input-file {
    display: block;
    border: none;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    opacity: 0;
}

Step 5 —

Now we will preview the image file conditionally. If you have dropped an image will render the image and or render the drag-and-drop area.

ImageContainer.js will be

import React from 'react';
import './ImageContainer.css';

const ImageContainer = () => {
    const [url, setUrl] = React.useState('');

    const onChange = (e) => {
        const files = e.target.files;
        files.length > 0 && setUrl(URL.createObjectURL(files[0]));
    };

    return (
        <div classname="image-container">
            {
                url ?
                    <img  classname="image-view" alt="Make an Image drag and drop with CSS in React" >



<h2>
  
  
  Step 6 —
</h2>

<p>Now we will import the ImageContainer component in our App.js and run our application using the npm start command and have fun while coding.</p>

<p><strong>App.js will be</strong><br>
</p>

<pre class="brush:php;toolbar:false">import './App.css';
import ImageContainer from './ImageContainer';

function App() {
  return (
    <div classname="App">
      <h2 id="Select-Image">Select Image:</h2>
      <div classname="image-area">
        <imagecontainer></imagecontainer>
      </div>
    </div>
  );
}

export default App;

In this tutorial, we showed you how to create a drag-and-drop feature for images using only CSS in React.

The above is the detailed content of Make an Image drag and drop with CSS in React. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Demystifying Screen Readers: Accessible Forms & Best PracticesDemystifying Screen Readers: Accessible Forms & Best PracticesMar 08, 2025 am 09:45 AM

This is the 3rd post in a small series we did on form accessibility. If you missed the second post, check out "Managing User Focus with :focus-visible". In

Create a JavaScript Contact Form With the Smart Forms FrameworkCreate a JavaScript Contact Form With the Smart Forms FrameworkMar 07, 2025 am 11:33 AM

This tutorial demonstrates creating professional-looking JavaScript forms using the Smart Forms framework (note: no longer available). While the framework itself is unavailable, the principles and techniques remain relevant for other form builders.

Adding Box Shadows to WordPress Blocks and ElementsAdding Box Shadows to WordPress Blocks and ElementsMar 09, 2025 pm 12:53 PM

The CSS box-shadow and outline properties gained theme.json support in WordPress 6.1. Let's look at a few examples of how it works in real themes, and what options we have to apply these styles to WordPress blocks and elements.

Comparing the 5 Best PHP Form Builders (And 3 Free Scripts)Comparing the 5 Best PHP Form Builders (And 3 Free Scripts)Mar 04, 2025 am 10:22 AM

This article explores the top PHP form builder scripts available on Envato Market, comparing their features, flexibility, and design. Before diving into specific options, let's understand what a PHP form builder is and why you'd use one. A PHP form

Working With GraphQL CachingWorking With GraphQL CachingMar 19, 2025 am 09:36 AM

If you’ve recently started working with GraphQL, or reviewed its pros and cons, you’ve no doubt heard things like “GraphQL doesn’t support caching” or

Making Your First Custom Svelte TransitionMaking Your First Custom Svelte TransitionMar 15, 2025 am 11:08 AM

The Svelte transition API provides a way to animate components when they enter or leave the document, including custom Svelte transitions.

Show, Don't TellShow, Don't TellMar 16, 2025 am 11:49 AM

How much time do you spend designing the content presentation for your websites? When you write a new blog post or create a new page, are you thinking about

Classy and Cool Custom CSS Scrollbars: A ShowcaseClassy and Cool Custom CSS Scrollbars: A ShowcaseMar 10, 2025 am 11:37 AM

In this article we will be diving into the world of scrollbars. I know, it doesn’t sound too glamorous, but trust me, a well-designed page goes hand-in-hand

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.