Search code examples
reasonreason-react

How to define reusable constants?


I have a Reason React component that looks like the following:

/* MyComponent.re */

let make = _children => {
    ...component,

    reducer: (action, state) => {
        switch (action) {
        | KeyDown(key) => switch (key) {
          | 13 => ReasonReact.Update(...)
          | _ => ReasonReact.NoUpdate
          }
        }
    },

    render: self => {
        <input _type="text" value=self.state.text
          onKeyDown=(event => self.send(KeyDown(ReactEventRe.Keyboard.keyCode(event)))) />
    }
};

Now I tried to refactor out the number 13 into a separate file:

/* Keys.re */

let enter = 13;

But I'm unable to use Keys.enter inside my switch statement in MyComponent.re. The error I get is:

Error: 275: <UNKNOWN SYNTAX ERROR>

I've also tried including the module directly inside MyComponent.re by adding:

module Keys = {
    let enter = 13;
};

at the top, but still get the same error.

My understanding of how modules work must be incorrect. What would be the correct way of accomplishing what I'm trying to do?


Solution

  • I don't think it's the issue with how the module is defined.

    You could do the switch like this:

    switch (key) {
    | key when key === Keys.enter => ReasonReact.Update(...)
    | _ => ReasonReact.NoUpdate
    }