React to Elm Migration Guide

This guide will help you learn and migrate to Elm with assumption you already know the basics of React. The Elm guide is great and will give you a thorough understanding of everything you need to know, in a good order.

This guide is different. Instead, we’re going to start with the fundamentals of JavaScript & React, and how you’d do the equivalent, if any, in Elm. If you already know React, we’ll use those firm groundings so you can feel more comfortable understanding “what Elm means” when they say something using language and concepts familiar to React developers.


What is React?

React is a library for ensuring your DOM is in sync with your data. However, one could argue it’s a framework in that it provides many fundamentals needed to build applications. There is enough features that you can adopt, that it is a sliding scale. Just want JSX and variables? Cool. Want a Context to emulate Redux? Cool. Want to swap out the render for something like Preact? Cool.

Modular to add and swap out parts with large community support to modify it to suit your needs.

It’s assumed you can write React in JavaScript. There are basic runtime typings enforced for component properties built into React. If you want something more, TypeScript support has been added as well.

A popular project, create-react-app, rose in popularity because of it’s ability to handle the compiler toolchain for you. Teams do not have to know about Webpack or JavaScript build targets such as CommonJS, ES6, or ES5. While they don’t have to maintain the core, for cyber security findings or build reasons, you/the team will still have to upgrade more than you might want to. Out of the box you get a simple development environment with the ability to save a file and see it live reload. Tests are setup and ready to go. Finally, a production build with all kinds of optimizations are there. Having 3 simple basic commands of start, test, and build give you all you need to build most apps.

While you can utilize npm, yarn is supported for those who want additional features that yarn provides.


What is Elm?

Elm is a strongly typed functional language, compiler, package manager, and framework. You write in the Elm language, and it compiles to JavaScript for use in the browser. The Elm compiler has 2 basic modes of development, and production. It optionally has a REPL if you want to test some basic code. The package manager uses it’s own website and structure using elm.json, instead of package.json. The framework is what Elm is most known for, and was the inspiration for Redux.

You code in Elm, in the Elm framework, install Elm libraries, and compile using the Elm compiler, into JavaScript. Most learning apps will compile to an HTML page which includes the JavaScript and CSS automatically. For more commonly advanced applications, you’ll just compile to JavaScript and embed in your own index.html. This often works better when you want to do additional HTML and CSS things to the main HTML file. There is a create-elm-app but it tends to violate the Elm philosophy of not using complex, hard to maintain JavaScript build tool-chains.

JavaScript and Elm Language Types

The following tables compare the basics of JavaScript to Elm.



“Hello World!”“Hello World!”
‘Hello World!”cannot use single quotes for strings
`Multiline string.`“””Multiline string”””
No distinction between characters and strings.‘a’
[1, 2, 3][1, 2, 3]


Objects / Records

{ x: 3, y: 4 }{ x = 3, y = 4 }
point.x = 42{ point | x = 42 }



function(x, y) { return x + y }\x y -> x + y
Math.max(3, 4)max 3 4
Math.min(1, Math.pow(2, 4))min 1 (2^4) sqrt numbers p => p.x ) .x points


Control Flow

3 > 2 ? 'cat' : 'dog'if 3 > 2 then "cat" else "dog"
var x = 42; ...let x = 42 in ...
return 42Everything is an expression, no need for return



'abc' + '123'"abc" ++ "123"
'abc'.lengthString.length "abc"
'abc'.toUpperCase()String.toUpper "abc"
'abc' + 123"abc" ++ String.fromInt 123


Nulls and Errors

42Maybe.Just 42
throw new Error("b00m") Result.Err "b00m"
42Result.Ok 42



You’ll often see JavaScript to emulate the above using Optional Chaining.

// has a value
const person = { age: 42 }
const age = person?.age

// is undefined
const person = { }
const age = person?.ageCode language: JavaScript (javascript)


type alias Person = { age : Maybe Int }
-- has a value
let person = Person { age = Just 42 }
-- is nothing
let person = Person { age = Nothing }Code language: JavaScript (javascript)

Function Composition (i.e. “Pipelines”)

Both languages below parse the following JSON String to get human names in a list.



The JavaScript Pipeline Operator proposal is at stage 1 at the time of this writing, so we’ll use a Promise below.

const isHuman = peep => peep.type === 'Human'
const formatName = ({ firstName, lastName }) => `${firstName} ${lastName}`

const parseNames = json =>
  .then( JSON.parse )
  .then( peeps => peeps.filter( isHuman ) )
  .then( humans => formatName ) ) Code language: JavaScript (javascript)


isHuman peep =
  peep.type == "Human"

formatName {firstName, lastName} =
  firstName ++ " " ++ lastName

parseNames json =
  |> Result.withDefault []
  |> List.filter isHuman
  |> formatName
  Code language: PHP (php)


Pattern Matching


The current pattern matching proposal for JavaScript is Stage 1 at the time of this writing.

switch(result.status) {
  case "file upload progress":
  case "file upload failed":
  case "file upload success":
    showError("Unknown error.")
}Code language: PHP (php)


case result.status of
  FileUploadProgress amount ->
    updateProgressBar amount
  FileUploadFailed err ->
    showError err
  FileUploadSuccess fileName ->
    showSuccess filename
  _ ->
    showError "Unknown error."Code language: JavaScript (javascript)


Hello World: React

  <h1>Hello, world!</h1>,
)</code>Code language: HTML, XML (xml)

Hello World: Elm

type Msg = Bruh
type alias Model = {}
update _ model =

view _ =
    div [] [ h1 [][ text "Hello World!" ] ]

main =
        { init = (\ () -> {})
        , view = view
        , update = update
Code language: JavaScript (javascript)


DOM Templates

JSX Element

const element = <h1>Hello world!</h1>;Code language: JavaScript (javascript)

Elm Element

let element = h1 [] [text "Hello World!"]Code language: JavaScript (javascript)

JSX Dynamic Data

const name = 'Jesse';
<h1>Hello {name}</h1>Code language: JavaScript (javascript)

Elm Dynamic Data

let name = "Jesse"
h1 [] [text "Hello " ++ name ]Code language: JavaScript (javascript)

JSX Functions

format = ({ first, last }) => `${first} ${last};

user = { first: 'Jesse', last: 'Warden' };

<h1>Hello {format(user)}</h1>Code language: JavaScript (javascript)

Elm Functions

format {first, last} = first ++ " " ++ last

user = { first = "Jesse", last = "Warden" }

h1 [] [text (format user) ] Code language: JavaScript (javascript)

JSX Image

<img src={user.avatarUrl} />Code language: HTML, XML (xml)

Elm Image

img [ src user.avatarUrl ] []Code language: CSS (css)

JSX Children

const element = (
    <h2>Good to see you here.</h2>
);Code language: JavaScript (javascript)

Elm Children

let element =
  div [] [
    h1 [] [text "Hello!"]
    h2 [] [text "Good to see you here."]
  ]Code language: JavaScript (javascript)



const Welcome = props => <h1>Hello {}</h1>welcome props = h1 [] [text "Hello " ++]
const element = <Welcome name="Sara" />let element = welcome { name = "Sara" }
const Greeting = ({ name }) => ( <div> <h1>Hello!</h1> <h2>Good to see you here, {name}!</h2> </div> )greeting {name} = div [] [h1 [] [text "Hello!"], h2 [] [text "Good to see you here, " ++ name ++ "!"]]


Event Handling

<button onClick={activateLasers}>
Activate Lasers
button [ onClick ActivateLasers ] [ text "Activate Lasers" ]
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>type Msg = DeleteRow Int
button [ onClick (DeleteRow 23) ] [ text "Delete Row" ]


Event Handling With State


class Toggle extends React.Component {
  constructor(props) {
    this.state = {isToggleOn: true};
  handleClick = () => {
    this.setState(state => ({ isToggleOn: !state.isToggleOn }));
  render = () => (
      {this.state.isToggleOn ? 'ON' : 'OFF'}
}Code language: JavaScript (javascript)


type alias Model = { isToggleOn : Bool }

initialModel = { isToggleOn = True }

type Msg = Toggle

update _ model =
  { model | isToggleOn = not model.isToggleOn }

toggle model =
      [ onClick Toggle ]
      [ if model.isToggleOn then
          text "ON"
          text "OFF" ]Code language: PHP (php)


Conditional Rendering


function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <UserGreeting />;
  return <GuestGreeting />;
}Code language: JavaScript (javascript)


greeting props =
    isLoggedIn = props.isLoggedIn
  if isLoggedIn then
    guestGreeting()Code language: JavaScript (javascript)




const numbers = [1, 2, 3, 4, 5];
const listItems = =>
);Code language: JavaScript (javascript)


let numbers = [1, 2, 3, 4, 5]
let listItems =
    (\number -> li [] [text (String.fromInt number)])
    numbersCode language: JavaScript (javascript)


Basic List Component


function NumberList(props) {
  const numbers = props.numbers;
  const listItems = =>    <li>{number}</li>  );
  return (

const numbers = [1, 2, 3, 4, 5];
<NumberList numbers={numbers} />Code language: JavaScript (javascript)


numberList props =
    numbers = props.numbers
    listItems =
        (\number -> li [] [text (String.fromInt number)])

let numbers = [1, 2, 3, 4, 5]
numberList numbersCode language: JavaScript (javascript)


Forms: Controlled Component


class NameForm extends React.Component {
  constructor(props) {
    this.state = {value: ''};

  handleChange = event => {
  handleSubmit = event => {
    alert('A name was submitted: ' + this.state.value);

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        <input type="submit" value="Submit" />
}Code language: JavaScript (javascript)


type Msg = TextChanged String | Submit

type alias Model = { value : String }

initialModel = { value = "" }
update msg model =
    case msg of
        TextChanged string ->
            { model | value = string }
        Submit ->
                _ = Debug.log "A name was submitted: " model.value

view model =
    form [ onSubmit Submit ][
            [ text "Name:"
            , input
              [type_ "text", value model.value, onInput TextChanged ] []]
        , input [type_ "submit", value "Submit"][]
    ]Code language: JavaScript (javascript)


Thinking In


React’s always been about the ease of creating components, then composing those components together into an application. Look at a UI, see the seems in your mind, and decide who will manage the various pieces of state.

  1. Mock
  2. Component Hierarchy
  3. Represent UI State
  4. Determine Where State Lives

1 – Mock Data

In React, you’ll mock the data you get from the potential back-end API or back-end for front-end that you’ll build. Below, we hard code some mock JSON so our components can show something and we can visually design & code around this data:

  {category: "Sporting Goods", price: "$49.99", stocked: true, name: "Football"},
  {category: "Sporting Goods", price: "$9.99", stocked: true, name: "Baseball"},
  {category: "Sporting Goods", price: "$29.99", stocked: false, name: "Basketball"},
  {category: "Electronics", price: "$99.99", stocked: true, name: "iPod Touch"},
  {category: "Electronics", price: "$399.99", stocked: false, name: "iPhone 5"},
  {category: "Electronics", price: "$199.99", stocked: true, name: "Nexus 7"}
];Code language: JavaScript (javascript)

2 – Component Hierarchy

Next, you’ll either create components from that data that you’ll represent, and see how each is a component with it’s own ability to represent the data visually and possibly handle user input… or do the same to a design comp given to you by a designer. Whether that’s the small components in the tree, or the bigger ones who bring it all together; that’s up to you.

Typically you’ll either eyeball the data and the components will start to visualize in your mind, OR you’ll see the design comp and start to slice the various parts into a component tree in your head.

  1. FilterableProductTable (orange): brings all components together
  2. SearchBar (blue): receives all user input
  3. ProductTable (green): displays and filters the data collection based on user input
  4. ProductCategoryRow (turquoise): displays a heading for each category
  5. ProductRow (red): displays a row for each product

3 – Represent UI State

Third, you’ll think strongly about state if you didn’t “figure out out” going through Step 2. Most data can be props, but if a component is controlled, perhaps it may have it’s own state that would help it interact with other components? Favor props, but use state where you need to encapsulate it into components. Whether using an Object Oriented class based approach, or a Functional one, often components will contain things you feel it’s best for them to manage internally.

4 – Determine Where State Lives

Lastly, identify who owns the source of truth. While many components can have their own internal state, the “state of the app” is typically owned by one or a select few. The interactions between these components will help you sus out where it should probably live, and how you’ll manage it (events, Context, Hooks, Redux, etc).



While many, myself included, wish to immediately jump to building components, Elm encourages thinking hard about your Model first. Elm’s types allow you to make impossible application states impossible, and simplifying how you represent things. The good news, if you screw this up, the Elm compiler has the best error messages in the industry and allows you to refactor without fear.

  1. Model Data
  2. Component Hierarchy
  3. Model Data Changes
  4. Handle Events

1 – Model Data

Step 1 is to model your data using Elm’s type system. Like React, some will either be dictated like an API, or it’s something you can customize from a BFF. However, this can be heavily influenced by your Designer’s comp as well.

type alias Product = {
  category : String
  , price : String
  , stocked : Bool
  , name : String }

type alias Model = {
  products : List Product

initialModel =
  Product {category = "Sporting Goods", price = "$49.99", stocked = True, name = "Football"}
  , Product {category = "Sporting Goods", price = "$9.99", stocked = True, name = "Baseball"}
  , Product {category = "Sporting Goods", price = "$29.99", stocked = False, name = "Basketball"}
  , Product {category = "Electronics", price = "$99.99", stocked = True, name = "iPod Touch"}
  , Product {category = "Electronics", price = "$399.99", stocked = False, name = "iPhone 5"}
  , Product {category = "Electronics", price = "$199.99", stocked = True, name = "Nexus 7"}
]Code language: PHP (php)

2 – Component Hierarchy

Almost the exact same as React, except there is no state in components; all state is your Model. Your FilterableProductTable, SearchBar, etc. are just functions that often take in the model as the first and only parameter.

3 – Model Data Changes

Even if you use Redux in React, you still reserve the right to occasionally keep internal component state. Not so in Elm; all state is in your model. That means your SearchBar (blue) would have a currentFilter : String on your model to capture what the current filter, if any, exists. You’d also have a onlyInStock : Bool for the checkbox. In React, both of those could be:

  • state in the component via this.state
  • state in the component via FilterableProductTable that you’d pass up via events
  • state in Redux
  • state in a Hook
  • state in a shared Context

In Elm, there is no question where: it’s in the model.

4 – Model Event Changes

In Elm, you do not need to decide “where UI state lives” because… all data lives in the Model. Instead, you need to decide how to change that data. For simple applications, it’s much like you’d do in Redux: create a Message containing the new data, and write code to change your model based on that message.

type Msg = ToggleOnlyInStock Bool

Now that you have your message, you’ll dispatch it when the user clicks the checkbox:

        [ ]
        [ input [ type_ "checkbox", onClick (ToggleOnlyInStock not model.onlyInStock) ] []
        , text "Only show products in stock"]Code language: CSS (css)

Lastly, change the data based on the message:

update msg model =
  ToggleOnlyInStock toggle ->
    { model | onlyInStock = toggle }




Using create-react-app, you’ll run npm start and your changes + compile errors will be reflected quickly in the open browser window.

For a production build, run npm run build.


Using elm-live, you’ll run elm-live and your changes + compile errors will be reflected quickly in the open browser window.

For a production build, run elm make with the --optimize flag. It’s recommended you additionally utilize uglifyjs first with compress then again with mangle, or some other compressor + mangler library.




Using create-react-app, you’ll run npm test which uses Jest internally. If you are dealing with a lot of data on the UI, or using TypeScript, use JSVerify for property tests. For end to end tests, Cypress is a great choice.


For Elm, unit tests often do not provide value given the compiler’s correctness. They’re better expressed using end to end tests and those are more likely to expose your race conditions. If you are dealing with a lot of data on the UI, use elm-test for property tests. While normally for unit-tests, it has fuzzers and shrinkers built in. For end to end tests, Cypress is a great choice.




While there are a variety of choices, react-router is one many settle on.

function Home() {
  return <h2>Home</h2>;

function About() {
  return <h2>About</h2>;

function Users() {
  return <h2>Users</h2>;

function App() {
  return (
              <Link to="/">Home</Link>
              <Link to="/about">About</Link>
              <Link to="/users">Users</Link>
}Code language: JavaScript (javascript)


Elm has routing built-in using the Browser library.

home =
  h2 [] [ text "Home" ]

about =
  h2 [] [ text "About" ]

users =
  h2 [] [ text "Users" ]

app =
  div [] [
    nav [] [
      ul [] [
        li [] [
          a [ href "/home" ] [ text "Home" ]
        , li [] [
          a [ href "/about" ] [ text "About" ]
        , li [] [
          a [ href "/users" ] [ text "Users" ]
Code language: JavaScript (javascript)


Error Boundaries


In React, you’ll build a component, or set of components, to wrap common error areas so in case a volatile part of the UI throws, you can handle it gracefully in the UI. First create a basic wrapper component:

class ErrorBoundary extends React.Component {
  constructor(props) {
    this.state = { hasError: false };

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.    return { hasError: true };

  componentDidCatch(error, errorInfo) {
    // You can also log the error to an error reporting service
    logErrorToMyService(error, errorInfo);

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    return this.props.children; 
}Code language: JavaScript (javascript)

Once you’ve got your component with logging and a fallback UI, you just wrap the dangerous components:

  <MyWidget />
</ErrorBoundary>Code language: HTML, XML (xml)


Elm does not have runtime errors (caveat: port dangers in section down below). The compiler will ensure that all possible errors are handled. This means you either model those error states in your model, ignore them with blank strings, or design different UI’s for those states.

Data not there? You must handle it:

case dataMaybe of
  Just data ->
    addProduct data
  Nothing ->
    -- Your UI or data must compensate somehow here.
    -- For now we just return all the products unchanged
    model.productsCode language: JavaScript (javascript)

HTTP operation you need to work fail? You must handle it:

case result of
  Error err ->
    { model | result = ProductSaveFailed err }
  Ok data ->
    { mdoel | result = ProductSaveSuccess data }

-- in UI
case result of
  ProductSaveFailed err ->
    errorViewAndRetry err
  ProductSaveSuccess _ ->
    goToProductViewCode language: JavaScript (javascript)




class Weather extends React.Component {
  constructor(props) {
    this.state = { temperature: undefined, loading: true };

  componentDidMount = () => {
    this.setState({ loading: true })
    .then( response => response.json() )
       ({ temperature }) => {
         this.setState({ temperature, loading: false, isError: false }) )
      error => {
        this.setState({ loading: false, isError: true, error: error.message })

  render() {
    if(this.state.loading) {
      return <p>Loading...</p>
    } else if(this.state.isError === false) {
      return <p>Temperature: {this.state.temperature}</p>
    } else {
      return <p>Error: {this.state.error}</p>
}Code language: JavaScript (javascript)


type Msg = LoadWeather | GotWeather (Result Http.Error String)

type Model
    = Loading
    | Success String
    | Failure Http.Error

init : () -> (Model, Cmd Msg)
init _ =
  ( Loading
  , loadTemperature
loadTemperature =
      { url = ""
      , expect = Http.expectJson GotWeather temperatureDecoder
temperatureDecoder =
  field "temperature" string

update msg model =
    case msg of
        LoadWeather ->
            (Loading, loadTemperature)
        GotWeather result ->
            case result of
                Err err ->
                    ( Failure err, Cmd.none )
                Ok temperature ->
                    ( Success temperature, Cmd.none )

view model =
    case model of
        Loading ->
            p [][text "Loading..."]
        Success temperature ->
            p [][text ("Temperature: " ++ temperature) ]
        Failure _ ->
            p [][text "Failed to load temperature."]Code language: JavaScript (javascript)


State Management


// Action Creator
const addTodo = text => ({ type: 'ADD_TODO', text })

// Dispatch
const goSwimming = () => store.dispatch(addTodo('Go Swimming.'))

// trigger from button
<button onClick={goSwimming}>Add</button>

// update model
const todos = (state = [], action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return state.concat([{ text: action.text, completed: false }])
      return state
}Code language: PHP (php)


-- Type for Todo
type alias Todo = { text : String, completed: Bool }

-- Message
type Msg = AddTodo String

-- trigger from button
button [ onClick (AddTodo "Go Swimming.")] [ text "Add" ]

-- update model
update msg model =
  case msg of
    AddTodo text ->
      { model | todos = List.append model.todos [Todo text, False] }
    ...Code language: JavaScript (javascript)