Search code examples
reasonreason-react

reason react how to handle event better?


I managed to get the event to update, using snippet of the web, I am having a really hard time to understand. Here is the entire snippet:

type state = {
    login: string,
    password: string
};

type action =
    | SetLogin(string)
    | SetPassword(string);


let component = ReasonReact.reducerComponent("Login");

let make = (_children) => {
    ...component,
    initialState: ()=> { login: "", password: "" },

    reducer: (action, state) =>
        switch (action) {
            | SetLogin (data) => ReasonReact.Update({...state, login: data })
            | SetPassword (data) => ReasonReact.Update({...state, password: data })
        },

    render: self =>
        <div>
            (ReasonReact.string("login"))
            <input
                value=self.state.login
                onChange={ev => self.send(SetLogin(ReactDOMRe.domElementToObj(ReactEventRe.Form.target(ev))##value))}
            />
            (ReasonReact.string("password"))
            <input
                value=self.state.password
                _type="password"
                onChange={ev => self.send(SetPassword(ReactDOMRe.domElementToObj(ReactEventRe.Form.target(ev))##value))}
            />

        </div>
};

I am looking at the onChange line in particular:

onChange={ev => self.send(SetLogin(ReactDOMRe.domElementToObj(ReactEventRe.Form.target(ev))##value))}

Isn't there a better way of doing this? This seems really convoluted..


Solution

  • There is nothing wrong with what you are doing and as far as I know, this is the only way. I tend to have a helper function like:

    let getValueFromEvent = event : string => (
                                                event
                                                |> ReactEventRe.Form.target
                                                |> ReactDOMRe.domElementToObj
                                              )##value;
    

    then it will clean things up a bit:

    <input
      value=self.state.password
      _type="password"
      onChange={event => self.send(SetPassword(getValueFromEvent(event)))}
    />