Setting a document title according to the context of your SPA can improve user experience. This way the user knows what part of the application is currently open/visible when your application is not the active tab.
In PureScript we can set the document title in two ways, a quick and dirty way via FFI and a proper type-safe way.
To set the document title directly we can define a foreign import (let's say in the file DocTitle.purs
import setDocumentTitle :: String -> Effect Unit foreign
As well we can provide a JavaScript implementation according to our import (in the File DocTitle.js):
export const setDocumentTitle = (title) => {
return () => {
window.document.title = title;
} }
To set a title we need to access the document first (which I cover in depth in "How to getElementById in PureScript":
import Web.HTML.HTMLDocument (toNonElementParentNode)
import Web.HTML.Window (document)
import Web.HTML (window)
import Web.DOM.NonElementParentNode (getElementById)
main :: Effect Unit
= do
main <- map toNonElementParentNode $ document =<< window maybeDoc
With the document we can now use the function setTitle from Web.HTML.HTMLDocument:
import Data.Foldable (for_)
import Web.HTML.HTMLDocument (toNonElementParentNode)
import Web.HTML.Window (document)
import Web.HTML (window)
import Web.DOM.NonElementParentNode (getElementById)
main :: Effect Unit
= do
main <- map toNonElementParentNode $ document =<< window maybeDoc
Thank you for reading this far! Let’s connect. You can @ me on X (@debilofant) with comments, or feel free to follow. Please like/share this article so that it reaches others as well.