0

I have this code for two input fields and a button: I have this code at the end:


<Form onFinish={onSubmit2URLs}>
<Form.Item name="url1" label="URL 1"> <Input /> </Form.Item>
<Form.Item name="url2" label="URL 2"> <Input /> </Form.Item>
<Form.Item>
<Button _type=#primary htmlType="submit" loading> {"Not a match"->React.string} </Button>
</Form.Item>
</Form>

How can I access the url1 and url2 values in my function below?

let onSubmit2URLs = (values: ReactEvent.Form.t) => {
   Js.log("These URLs are not a match:")
   Js.log(values)
}

I tried accessing values.url1 but that didn't work.

1 Answers1

0

Since you're not providing the definitions of Form, Input etc. I can only assume that it renders as <form> and <input> elements. This is also very non-idiomatic React code, and while it's certainly possible to do exactly what you ask for, it's not very straight-forward and I would recommend that you refactor your code to be more idiomatic, using component state and controlled components instead of using implicit state stored in the DOM. This will make it much easier to reason about and evolve your code over time to add new features.

You can get the value of each input quite easily, store that in the component state, and use the stored state on submit:

type state = {
  url1: string,
  url2: string,
}

@react.component
let make = () => {
  let (state, setState) = React.useState(() => {url1: "", url2: ""})

  let getValue = event => ReactEvent.Form.target(event)["value"]
  let onSubmit = _event => Js.log(state)

  <form onSubmit>
    <input
      value=state.url1
      onChange={event => setState(state => {...state, url1: event->getValue})}
    />
    <input
      value=state.url2
      onChange={event => setState(state => {...state, url2: event->getValue})}
    />
  </form>
}
glennsl
  • 28,186
  • 12
  • 57
  • 75