Search code examples
reactjskotlin-jskotlin-js-interop

How to submit a form with KotlinJS and React?


I want to display a file selector and a submit button. The file is only to be submitted once the button is clicked. The submit/action target is on another server though. I looked at react examples, but I can't figure out the exact method on how to realise this with KotlinJS and React.

The duplicates in formMethod and onSubmitFunction are just me trying and seeing what sticks. I also tried adding method = FormMethod.post, encType = FormEncType.multipartFormData directly to the form, but it didn't help. It doesn't even output the debug print.

EDIT: I do not need to do something with the file otherwise and want to leverage the default form functionality for the upload. The other server is also mine and has a simple html/http upload where this suffices:

<form method="post" enctype="multipart/form-data">
      <input type="file" name="file">
      <input type="submit" value="Upload">
</form>

ENDEDIT

EDIT2: I changed the code a little and now it refers to the other server, but does not append any files.

private fun RBuilder.render() {
    form(
        method = FormMethod.post,
        encType = FormEncType.multipartFormData,
        action = "https://otherserver.com/upload"
    ) {
        styledInput {
            attrs {
                type = InputType.file
                accept = ".zip"
                multiple = false
           }
        }
        styledInput {
            attrs {
                type = InputType.submit
                value = "Test"
            }
        }
    }
}

Solution

  • It seems like in this case the name parameter is strictly required.

    The following works:

    private fun RBuilder.render() {
        form(
            method = FormMethod.post,
            encType = FormEncType.multipartFormData,
            action = "https://otherserver.com/upload"
        ) {
            styledInput {
                attrs {
                    name = "upload"
                    type = InputType.file
                    accept = ".zip"
                    multiple = false
               }
            }
            styledInput {
                attrs {
                    type = InputType.submit
                    value = "Test"
                }
            }
        }
    }