React Drag And Drop (dnd-kit) | Beginners Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this tutorial we'll learn how to easily add drag and drop to your react project we'll create a to-do list where you can add new tasks check them off using the checkboxes and then sort them by dragging them and we'll also enable keyboard controls and touch controls for mobile devices but before we begin we need to decide which library is the best the most commonly used one is react DND but to be honest the documentation is not that good and it's quite verbose and hard to use as you can see from the code below then there's react beautiful d and d and it's by atlassian which is the company that made jira and owns Trello so it's really good but the issue is that it's no longer being maintained and supported so what that means is when there's a new version of react or any major changes in react this won't be updated and it could break and won't work with your new app which is why for this tutorial we'll be using DND kit DND kit is a very easy to ous library it's being maintained actively it's got very good documentation and it has many features as well and as you can see on npm it's got a rising number of installs over the past few months so with that said let's see how to use DND kit in our project so we have vs code opened up and we have a basic react application set up using V in our app.jsx we just have an H1 tag which has my tasks written inside it inside app.css we just have some styling to Center everything and add some margin to our app and then inside index. CSS we are just setting the font family and removing any margin and padding on all elements so to install dndd Kit we'll stop our server over here and we'll write npm install at DND dkit /c core which contains the main core of the library then we'll install at dn- kit SL utilities which contains some functions which are very useful when using DND kit and then lastly We'll add DND dkit SL sortable this basically makes it possible to make draggable elements reorderable inside a column which we'll see when we create the app so we'll hit install and we'll do npm run Dev again so now that we have everything installed we'll go back into app.jsx and we'll say import dndd context from at DND dkit slore and whenever you're adding anything which will involve Dragon drop in your project you'll need to have a DND context tag around it so we'll go below the heading over here and we'll say dndd context and close that tag now the first attribute we'll need to Define is Collision detection and this basically tells DND kit whenever we drag an element inside a certain area how to decide which area this should go towards when it's left by the mouse so we'll use an algorithm called closest corners and that will be imported from DND kit core so now that that's defined what we need to do is add some State into our application and Define the different objects which can be dragged so we'll go to the top over here and say const tasks and set tasks is equal to use State and our state will be an array which I'll just paste over here so as you can see it's an array of objects and each object has an ID and a title so the title is what will be shown on the screen and the ID is really important because each object inside our state needs to have an ID for dndd kit to work and each object's ID should be unique so now that we have the context and we have the objects which we want to render we actually need to add some stuff which we and render so let's start with the column which will be there in the center and will contain all our draggable elements so we'll go into SRC and create a components folder and create a column folder for our column component we'll say column. jsx and column. CSS inside column. jsx I'll just write rafc to create the column component and it'll take in a prop which will be the tasks which is the array of objects and we'll just go in app.jsx and inside the DND context which is if we remember where everything has to be we'll say column which will get Auto imported and for the tasks uh prop we'll pass in the tasks which we've defined and we see that the column is being rendered now so what we'll do is add a class name of column to this and we'll also import slash colum do CSS and we'll add the following styling which just sets the background color at the border radius and makes it a flex item back inside column. jsx uh we actually want to use the tasks array now so inside this div We'll add uh some uh logic so we'll say tasks. map we'll take the current task and we'll say render out a dis and inside there just render the task. title and give it a key of task. ID and we see that the tasks are being rendered out now to make these draggable and droppable we need to do two things first we need to tell DND kid that this column is an area where stuff can be dragged and dropped and then we need to tell DND kid that these individual items can be picked up by the mouse and dropped in places so let's get started with the column and to tell dndd kid that this is an area where stuff can be dragged and dropped what we need to do is go to the top and say import sortable context from DND kit / sortable inside this div we'll add the sortable context tags and wrap our JavaScript around with it we need to tell sortable context which items to keep track of so items will be equal to tasks so the logic is being handled by the items prop and the rendering is being handled by the JavaScript over here and then we need to tell it what strategy to use for sorting our elements so we'll use something called vertical list sorting strategy since we do have a vertical list right now if you had a horizontal list you would you would use that instead so we'll go into the components folder and create a new folder called task and we'll create task. jsx and task. CSS in task. jsx we'll write rafc and create the component and we'll take in a few props which will be the ID and the title of this task then back in column. jsx all we need to do is delete this div over here write down task which will get Auto imported give it the ID which is equal to the current task. ID give it the title which is equal to the current task. title and in DND kit each object needs to have a key as well so we'll give it a key of task. and save that now of course we need to go back here and actually use the title and the ID so over here we'll firstly add a title and before that we also add an input since we want to add a checkbox we'll say input type is equal to check box and class name is equal to check box as well and then this div will have a class name of task then we can go into task. CSS and I'll paste in The Styling the task styling just adds some background color to the task and um it makes the borders rounded and makes it a display flex and then for the checkbox that just in increases the width and the height of the element and inside task. jsx we'll import the CSS so import. SL task. CSS and we see now that everything looks a lot better but you'll see that we still can't drag the elements and that's because we need to tell dndd kit that these are dragable elements and to do that we'll go to the top and say import use sortable from DND kit Das sortable we'll come to the top of our component here and we'll say use sortable and pass in the ID of this um given task and this will return a few uh variables so we'll say const it will return some attributes some listeners a function called set node ref the transform property and then the transition property so to get started with we'll just go to our div over here and we'll first assign it a ref and make it equal to the set node ref and this just attaches a reference to this given element which a d and kit can keep a track of we'll spread the attributes and we'll also spread the listeners and save that now one more thing we need to do is um add a style attribute because that's how dndd kit will control what the element looks like while we're dragging it so what we need to do for that is create a con style object and pass it to our div over here so style is equal to style and inside this object we need to add a few properties so transition which we got from you sortable we just pass that that in here and then for transform we can't pass it indirectly because the transform variable which we get back is in the same type as the CSS variable which we need so to do that we we import the Cs s class from at DND dg/ utilities and then we say transform should be css. transform do2 string and then pass in the transform variable which we got and save that now if we go back to our app we can see that we can drag the different elements but if we let go we'll see that it goes back to its original position and that's because we need to add a final function to our configuration by the way if you're liking the video till now please consider subscribing and joining the Discord server mentioned in the comment down below or in the description to ask questions give feedback and meet other developers so the function we need to add is an app. GSX and we basically need need to tell DND context what to do when a certain element is dropped in a position so it'll be inside DN context the property is called on drag end and we need to pass a function we'll create a function called handle drag end so we'll come over here and we'll say const handle drag end is equal to it takes in an event and then we get two properties from the event called active and over and we say is equal to event and active is the element which we're currently dragging and over is the element which will be replaced once we let go of the active element so we'll first check if active do ID is equal to over. ID which means it's being let go in the same position that it was in the beginning we just just return and won't do anything otherwise we'll say set tasks because we need to update the array of our tasks we'll take in the current value and we'll need to return the new value of this variable so before that we'll create a helper function which we'll need so we'll say const get task position and what this does is it basically takes the ID of the task and it goes through the tasks array and finds the index where the given ID occurs because right now it's 1 2 3 but it could be rearranged later on and we need to find out the index in the array where a given ID is so find index get the task at the current position and if task. ID is equal to the given ID then it will return the index now we go inside this function back again and we say const original pause is equal to get task pause in active. ID and this gets us the position of the element before it was dragged and const new pause is equal to get task PA over. ID and this gets us the new position where it should be after the array is updated then we'll say return and D andd gives us a useful utility function which basically updates the array based on the original and the new position so it's called array move and we'll Auto Import that we pass in the array which needs to be updated the original position and the new position and save that and if we go back to our application and refresh we see that if we drag an element it stays where it was dragged to now that's basic drag and drop completed but this won't work on mobile devices and if you want to use the keyboard for example to move stuff around that won't work either and for that you need to use something called sensors so over here we'll say const sensors and equal to use sensors and that will be Auto imported from D andd kit and then inside that we can pass a bunch of different sensors which we want to use so for now we'll say use sensor which is a different import and we'll pass in the pointer sensor which is the default sensor which is used we'll say use sensor and touch sensor and we'll say use sensor keyboard sensor and we need to pass in an object over here called coordinate getter and we'll pass in sortable keyboard coordinates from DND kit and then to use these sensors we just go into DND context and say sensors is equal to aners and save that now if you go into your application and you press enter over an element and control hold and press up and down you can move it because of the keyboard sensor and if you go into the device mode and choose pixel 7 for example you can touch the element and move it as well and one thing to keep in mind is that when you do this you need to go into task. CSS and make sure your draggable element has touched - action equal to none now that all the drag and drop stuff is done we lastly add an input which can add elements as a Finishing Touch so we'll say const add task is equal to Tak in the title as a string and say set tasks Tak in the current array and return a new array we'll spread the old values of the tasks and add in a new object with the ID equal to tasks do length + 1 because the ID will be four if we add another element which is 3 + 1 and we'll say titles and save that now we need to create an input element so we'll go into the conference folder and create input input. jsx input. CSS inside input. jsx we'll say RFC and we'll go back into app.jsx and on top of the column we'll just import the input and we'll say on submit is equal to add task back inside input. jsx we'll take in an on submit function we'll also have const input and set input is equal to use State it's an empty string we'll say const handle submit this will get run whenever the button is clicked and we'll say if there is no input then just return but if there is call the onsubmit function pass to us and pass in the input value currently and after that's done clear out the input field and we'll import use State over here now we'll actually add the elements so out the outer div we'll give it a class name of container then we'll create an input tag we'll uh give it a type of text class name of input value of input which we've defined at the top and then on change take the event and say set input and pass an e. target. value and then below that we add a button it says add and then on click we say handle submit which is the function over here and we have the element over here let's just add The Styling so in input. CSS We'll add The Styling um this just makes the container a flex item gives some border and padding to the input and add some color and uh border and padding to the button as well and we'll import that in import. jsx so import. SL input. CSS and for the button we also have have to add the class name so class name button and save and now we can say new task it gets added to our list and we can drag and drop it as if it were already there so that is the best and easiest way to add drag can drop to your application and you also learned how to make a sample application using it so I hope you liked what you learned if you did please do consider subscribing liking and sharing the video and to stay updated ask questions and give any feedback and meet other developers do consider joining the Discord server uh link down [Music] below
Info
Channel: Code Complete
Views: 15,846
Rating: undefined out of 5
Keywords: drag and drop, dnd-kit, react, beginners tutorial, javascript
Id: dL5SOdgMbRY
Channel Id: undefined
Length: 17min 27sec (1047 seconds)
Published: Thu Jan 18 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.