[solved] How can I pass Reason React's `self` into another function?

reasonreact

#1

I was trying to clean up my react component by moving some of the functions outside of render and when I pass self down into a function, it loses it’s scope and I get an error: The record field send can't be found.. I suppose it needs a type in the handleSubmit function but when I look at the reason-react interface file I can’t seem to find one (everything just references send(a,b,c)).

Minimal example:

let handleSubmit = (self, event) => {
  SF_Utils.preventDefault(event);
  self.send(Submitted);
  Js.log("submit");
};

let make = (children) => {
  ...component,
  initialState: getInitialState,
  reducer: (action, state) => ... },
  render: self => {
    <div className="sf-form-container">
      (
        ReasonReact.createDomElement(
          "form",
          ~props={"className": "sf-form", "onSubmit": handleSubmit(self)},
          children,
        )
      )
    </div>
  },
};

However, after much tinkering, I’ve discovered that passing in self.send does work fine. ¯\_(ツ)_/¯ However, I would still like to pass down self if possible so that I can access self.state for other use cases.


#2

You can solve this by using the handle callback handler and writing something like this:

let handleSubmit = (event, self) => {
  SF_Utils.preventDefault(event);
  self.send(Submitted);
  Js.log("submit");
};

let make = (children) => {
  ...component,
  initialState: getInitialState,
  reducer: (action, state) => ... },
  render: self => {
    <div className="sf-form-container">
      (
        ReasonReact.createDomElement(
          "form",
          ~props={"className": "sf-form", "onSubmit": self.handle(handleSubmit)},
          children,
        )
      )
    </div>
  },
};

#3

Ah… clearly I need to re-read all the reason-react docs! Thanks so much!
One thing to note for future readers, I had to change self.send(Submitted) to self.ReasonReact.send(Submitted) as well.


#4

Don’t feel so bad. I had some issues with the docs when it came to using the self.handle stuff.