Open
Description
Follow-up to #197
The existing code produces a warning in the dev console with this strategy:
main :: Effect Unit
main = do
body <- body =<< document =<< window
case body of
Nothing -> throw "Could not find body."
Just c -> do
buttons <- mkButtons
render (buttons {}) (HTMLElement.toElement c)
Here's a warning-free option that's a little more verbose:
-- App setup
main :: Effect Unit
main = do
root <- createRootElement
buttons <- mkButtons
render (buttons {}) root
-- DOM helper, creates an element we can mount
-- the React app into
createRootElement :: Effect Element
createRootElement = do
doc <- document =<< window
body <- maybe (throw "Could not find body element") pure =<< HTMLDocument.body doc
root <- createElement "div" $ HTMLDocument.toDocument doc
root # Element.setClassName "app-root"
void $ appendChild (Element.toNode root) (HTMLElement.toNode body)
pure root
It would be most ideal to have a utility function that handles this common pattern:
main :: Effect Unit
main = renderInRoot $ mkButtons {}
Tracking a proposal to add this utility function to the React library in purescript-react/purescript-react-basic-dom#8
Also wondering if we should make code that's reused between recipes more generic (even if scripts/newRecipe.sh
) handles this renaming for us. For example, removing "buttons" where possible:
myComponent :: Component {}
myComponent = do
component "MyComponentName" \_ -> React.do
-- button-specific code here
main :: Effect Unit
main = renderInRoot $ myComponent {}