Search code examples
styled-components

Styled Components in React: <Form /> onSubmit handler does not work


The Form Component is of type styled.form`` and is defined outside the component on the bottom of the file. The issue: The onSubmit event handler does not work. Official docs don't have anything on onSubmit.

   const submitHandler = e => {
      e.preventDefault()
      console.log(e) // nothing appears in console
   }


/// ... in JSX:

         <Form onSubmit={submitHandler} >
            <Input placeholder="YouTube URL" required name="input" onChange={changeHandler} />
            <Button type="submit" >
               <Icon /> <Span>Add Song</Span>
            </Button>
         </Form>

//... styled form defined at the bottom of the file below export default statement:

const Form = styled.form`
   display: flex;
`

A Solution that I have found is to attach the submitHandler to an onClick event of a button inside a form. I'm not sure about that as I have never in the past used the button for submitHandlers (and I don't think it even works in pure React).

So, this would work:

<Button type="submit" onClick={submitHandler} >Submit</Button>

Solution

  • The problem is with the button. You have the <Button> component implemented as a <div> styled component. Having type="submit" on a <div> has no effect as far as the form is concerned. That's why the submit event never got fired.

    So, you can change your code as follows:

    1. const Button = styled.button
    2. remove onClick from the button and change the onSubmit simply to submitHandler:
        <div>
          <Form onSubmit={submitHandler}>
            <Input
              placeholder="Paste YouTube URL here"
              required
              name="input"
              onChange={changeHandler}
            />
            <Button type="submit">
              <Icon /> <Span>Add Song</Span>
            </Button>
          </Form>
        </div>
    

    You will see the results in the UI, as the form will start applying validation (because of the required attribute on the input), and also in the console where the handler will log.