Resetting a Slate.js editor to an empty state

Josh Sherman
1 min read
Software Development JavaScript TypeScript

I’ve been messing with Slate.js and happen to be using it in the context of having a persistent editor on the page that can be used post from. It’s sort of like a chat’s message input, it’s always there, and when you submit it, it resets back to it’s original state.

When your destroying a component after submit, this isn’t a problem, but in my particular use case it was, so I needed to figure out how the heck to clear out the editor and reset it back to it’s original glory.

Unfortunately, Slate.js doesn’t have a command to just reset the editor back to birth, and setting the value to just an empty string or null doesn’t fit into the types for what a proper editor value looks like.

After poking around a bit to see what the editor value looks like when it’s initially created, I grabbed said array and dictionary and simply used it as my “initial value” that I used to both initialize the state, as well as reset it.

Said initial value looks like this:

const initialEditorValue: Node[] = [{
  type: 'paragraph',
  children: [{ text: '' }],
}];

To use it to initialize your state (via hooks):

const [editorValue, setEditorValue] = useState(initialEditorValue);

And to reset it (usually done after you’re done submitting the editor’s value:

setEditorValue(initialEditorValue);
Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Born again Linux user. Founder of Holiday API, Backend Engineering Manager and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Pears and Perils
Antifragile: Things That Gain from Disorder
Grinding It Out: The Making of McDonald's

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles