Drag and Drop Material-UI Component in a React App

Today, we will see how to add drag and drop functionality to the Material-UI components within a React app.

Full Transcript

Hi there, welcome to today's video and I am Deeksha from Bonsaiilabs.

Today, we will see how to add drag and drop functionality to the Material-UI components within a React app.

As usual, we will be using CodeSandbox for this demo. I already bootstrapped a React project and added the latest dependencies for @material-ui/core and react-draggable.

Let's remove this boilerplate code that came with the app. We will write our own component.

Our goal is to have 2 cards on this web page that you can drag and drop anywhere.

So let's go ahead and create a function component with name <DraggableCard> with 2 props - text and bgColor which is nothing but the background color just to give them a different look and feel.

It returns a Card component from Material-UI and we will add an inline style to it. Let's say we want the width of this card to be 50%, backgroundColor should be the one passed in props and color of the text on this card should be white.

Inside this Card, we will have a button component with variant="text" and label "BUY". Let's also use Material-UI Typography component to display the text with variant="h6".

Now, we also added the react-draggable library and that was for a purpose. Let's import Draggable from react-draggable and all we need is to wrap our <Card> component inside this <Draggable> component we just imported.

And call <DraggableButton> component inside here inside the <App> component. The first card with text Drag and the bgColor slighly orange. And the second card with text Drop and bgColor a variation of blue.

And there we go! We can now drag these cards anywhere on the screen. Usually this kind of functionality is needed when you are creating dashboards or writing a customized software that gives your users an ability to drag and drop things around.

Now if you don't want this card to be Draggable. Instead you need an ability to drag and drop the button component anywhere inside this card. You can do so by removing this wrapper around the card and instead quickly create a <DraggableButton> component that wraps the Material-UI button inside <Draggable> and simply call this <DraggableButton>.

If you want to know how to do that, I have added a function in the Codesandbox already. So just click on the sandbox and call that function instead of <DraggableCard> and you will be good to go.

This is one of the questions we have been repeatedly receiving from Material-UI learners so hopefully this video provide some help.

Alright guys! Thanks for watching and I will see you in the next video.