Create draggable components in ReactJS using React-Draggable module

draggable components ReactJS React-Draggable Draggable module

In this tutorial, we’ll explore React-Draggable in depth by creating a note list with draggable components. Let’s get started!

Installing React-Draggable

Before installing React-Draggable, make sure you have a React project set up on your local machine. Navigate to the project and run the following command in the terminal:

npm install react-draggable

Now, we’ll import the  <Draggable/> component from the library. To add movement to an element or a component, we can simply wrap the <Draggable/> component around it.

Add the following code to App.js:

import Draggable from "react-draggable";

function App() {
  return (
 <Draggable>
      <div>I can now be moved around!</div>
    </Draggable>
  );
}

export default App;

The code above will render the following output in the browser:

Draggable Components React Draggable

Now that you know how the React-Draggable library works, let’s get started on our note list.

  • Create a project run this command:
npm install -g create-react-app
  • Then move into the newly created directory:
cd <project name>
  • Install required library :
npm install --save react-draggable uuid or yarn add react-draggable uuid
  • After creating components folder in src/components and pages folder in src like src/pages
  • After that create a components folder then create header component src/components/header.js and Add the following code to header.js:
import React from "react";

export default function Header({ handleSubmit }) {
  return (
    <div className='header'>
      <button onClick={handleSubmit} className='addButton'>
        Add Note
      </button>
      <p>Notes</p>
    </div>
  );
}

The </button> gets the handleSubmit function as a prop, which will show the AddForm element. With our header set up, let’s create the AddNoteForm element:

AddNoteForm element

Add the following code to AddNoteForm.js:

import React, { useState } from "react";
import { v4 as uuidv4 } from "uuid";

export default function AddNoteForm({ setAddItem, addItem, notes, setNotes }) {
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    let newNote = {
      id: uuidv4(),
      name: name,
      description: description,
    };
    setNotes([...notes, newNote]);
    setAddItem(!addItem);
  };
  return (
    <div className='addForm'>
      <form onSubmit={(e) => handleSubmit(e)}>
        <input
          type='text'
          placeholder='Name'
          onChange={(e) => setName(e.target.value)}
        />
        <input
          type='text'
          placeholder='Description'
          onChange={(e) => setDescription(e.target.value)}
        />
        <button type='submit'>Add</button>
      </form>
    </div>
  );
}

In the code block above, we have input fields that will take relevant data provided by users. Each note has an idnamedate

When the form is submitted, each note will be added to the note list that we created in App.js. When the form is submitted successfully, it will be hidden.

notes element

Add the following code to notes.js:

import React from "react";
import Card from "./../components/card";
export default function Complete({ notes, addNote }) {
  return (
    <>
     {notes.map((e) => (
         <Card currentNote={e} notes={notes} addNote={addNote} />
     ))}
    </>
   );
}
  • After that  create card component src/components/card.js and Add the following code to card.js:
import React from "react";
import Draggable from "react-draggable";
export default function Card({ currentNote, notes, addNote }) {
return (
   <Draggable grid={[10, 10]} axis='both' bounds='parent'>
     <div className='card' key={currentNote.id}>
      <div className='heading'>
        <h3>{currentNote.name && currentNote.name}</h3>
        <img
           onClick={() => {
           const newNoteList = notes.filter((item) => {
           if (item.id != currentNote.id) {
               return item;
           }
           });
             addNote(newNoteList);
           }}
            src='https://toppng.com/uploads/preview/recycling-bin-vector-delete-icon-png-black-11563002079w1isxqyyiv.png'
            style={{ height: "20px", width: "20px" }}
         />
      </div>
        <p>{currentNote.description}</p>
      </div> 
    </Draggable>
  );
}

The <Card/> the component gets three props, which are required for rendering and deleting logic.

The parent div <Draggable> is imported from our library, making the whole card moveable. By default, you can move the card anywhere on the screen. However, to prevent it from going outside of its parent element, we’ll provide a value to a bounds prop.

Deleting the Note

For removing a note, add the code below:

const newNoteList = notes.filter((item) => {
   if (item.id != currentNote.id) { 
       return item;
   }
});

addNote(newNoteList);

The code block above gets the entire list of notes from App.js, then creates a new list that excludes the current note. Next, let’s import each component in App.js

App.js

import "./App.css";
import { useState } from "react";
import Header from "./components/header";
import Note from "./pages/notes";
import AddNoteForm from "./pages/addNoteForm";
function App() {
   const [notes, setNotes] = useState([]);
   const [addItem, setAddItem] = useState(false);
   const handleSubmit = () => {
      setAddItem(!addItem);
   };
   const addNote = (note) => {
     setNotes(note);
   };
 
  return (
    <div>
      <Header handleSubmit={handleSubmit} />
      <div className='mainGrid'>
         <div className='column'>
             <Note notes={notes} addNote={addNote} />
         </div>
        {addItem && (
            <AddNoteForm
              addItem={addItem}
              setAddItem={setAddItem}
              notes={notes}
              setNotes={addNote}
            />
         )}
      </div>
    </div>
  );
}

export default App;

Finally, we’ll add styles to our note list. Add the following code in App.css:

.mainGrid{ 
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    flex-wrap: wrap;
    height: 100vh;
}
.header{
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    flex-wrap: wrap;
    background-color: #7363ba;
    color: #fff;
}
.column{
    width: 100vw;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    overflow: hidden;
}
.card{
    border: 1px solid black;
    background-color: white;
}
.card p{
    font-size: 10px;
    width: 30vw;
}
.heading{ 
    display: flex;
    flex-direction:row;
    align-items: center; 
    justify-content: space-between;
}
.addButton{
    position:absolute;
    top: 1%;
    left: 1%;
}
.addForm{
    height: 60vh;
    width: 60vw; 
    background-color: #7363ba;
    display: flex;
    align-items: center;
    justify-content: center; 
    position: absolute;
    left: 20%; 
    top: 20%;
}
.addForm form{
    display: flex;
    flex-direction: row;
    flex: 1;
    align-items: center;
    justify-content: center;
    flex-direction: column;
}
.addForm form input{
    width: 60%; 
    margin: auto;
    height: 44px;
    border-radius: 10px;
    margin-bottom: 10px;
}
.addForm form button{
    color: #fff;
    width: 30%;
    margin: auto;
    height: 44px;
    background: #30dc12c5;
    border-radius: 10px;
    border: none;
}
button {
   color: #fff;
   height: 34px;
   background: #30dc12c5;
   border: none;
}

In this tutorial, we used React-Draggable to create an note list. To learn more about React-Draggable, be sure to visit the GitHub page.

About the author
Code solution

info@codesolution.co.in

Discussion
  • 0 comments

Add comment To Login
Add comment