module ProfileFormFields = %lenses( type t = { nickname: string, age: int, } ) module FormFields = %lenses( type state = { name: string, email: string, profiles: array, } ) module Form = ReForm.Make(FormFields) module ReFormPresenter = { @react.component let make = () => { let handleSubmit = ({state}: Form.onSubmitAPI) => { Js.log2("submit >", state.values) None } let form = Form.use( ~initialState={name: "", email: "", profiles: [{nickname: "", age: 0}]}, ~onSubmit=handleSubmit, ~validationStrategy=OnDemand, ~schema={ open Form.Validation schema([string(~min=3, Name), custom(({profiles}) => { let errors: array = profiles ->Array.mapWithIndex((index, profile) => if profile.nickname == "" || profile.age <= 0 { let error: ReSchema.childFieldError = { error: "Invalid profile", index, name: "???", } Some(error) } else { None } ) ->Array.keepMap(x => x) switch errors { | [] => Valid | _ => NestedErrors(errors) } }, Profiles), email(~error="Invalid email", Email)]) }, (), )
{"Sign up"->React.string}
{switch Field(Name)->form.getFieldError { | None => React.null | Some(message) =>
{message->React.string}
}}
{switch Field(Email)->form.getFieldError { | None => React.null | Some(message) =>
{message->React.string}
}}
{form.values.profiles ->Array.mapWithIndex((index, profile) =>
Int.toString} className=%twc("flex flex-row")> form.arrayUpdateByIndex(~field=Profiles, ~index, {...profile, nickname}) )} /> {switch Field(Profiles)->form.getNestedFieldError(index) { | None => React.null | Some(message) =>
{message->React.string}
}} Int.toString} onChange={ReForm.Helpers.handleChange(age => { let age = Int.fromString(age)->Belt.Option.getWithDefault(0) form.arrayUpdateByIndex(~field=Profiles, ~index, {...profile, age}) })} /> {switch Field(Profiles)->form.getNestedFieldError(index) { | None => React.null | Some(message) =>
{message->React.string}
}}
) ->React.array}
} }