Use React DND Beautiful to Create a Drag and Drop Component in a Next.js App

If you already have a Next app, the first step to setting up a drag and component is to install React DND Beautiful.

Install

Depending on if you’re using yarn or npm the command will be:


yarn add react-beautiful-dnd
or
npm install react-beautiful-dnd --save

Next, I created a new page in my next app for demonstrating drag-and-drop components.  I did this by creating a new file in the pages directory. In that file, I began by importing some key functions from react-beautiful-dnd.


import {
DragDropContext,
Draggable,
DragUpdate,
Droppable,
resetServerContext,
} from 'react-beautiful-dnd'

Comparison: Next vs. React App

There’s an important thing to know that will be different for a Next app compared to a traditional React app. Due to server-side rendering, we need to manage some server states to get the library to work. We can do that by implementing getServerSideProps, which is a Next lifecycle function. In this function, you need to call the resetServerContext we imported earlier. For me, that looked like this:


export const getServerSideProps: GetServerSideProps = async (ctx) => {
resetServerContext()
return { props: {} as never }
}

After I’d implemented this reset, I ran into another problem. The React DND could not be rendered ahead of time on the server. It may be possible to get this working, but I had to work around it.

I did that by creating some local state in my component. As you can see, I initialize that to false.


const [isBrowser, setIsBrowser] = React.useState(false)

Then, I wrapped my entire component in a check to see if the environment is the browser:


return ( 
isBrowser && (
  [actual Component Code]
))

Adding a useEffect Hook

Finally, I need a way for isBrowser to become true once the app is in the browser. To do this, I added a useEffect hook. This use effect has an empty second parameter, so it is only run once on page load.


React.useEffect(() => {
setIsBrowser(
window !== undefined && window !== null && typeof window != 'undefined'
)
}, [])

Those are the main differences between a Next app and a React app in how they use React DND Beautiful. If you keep these adjustments in mind, you can then follow their guides here: https://egghead.io/courses/beautiful-and-accessible-drag-and-drop-with-react-beautiful-dnd.

Conversation

Join the conversation

Your email address will not be published. Required fields are marked *