Skip to content
Advertisement

Styled Components with React – form onSubmit not working

So I wanted to make a Styled Components form component and then use it in a bigger react component. Problem is, when I wanted to attach an onSubmit, it didn’t really work. My Styled Components form component:

const FormWrapper = styled.form`
    margin: 2vw 0 0;
    display:flex;
    flex-direction:column;
    align-items:center;
`;

My react parent component:

const Form = () => {

  const handleSubmit = (e)=>{
    e.preventDefault();
    console.log('submitted');
  };

  return(
      <FormWrapper>
          <Input name="username" placeholder="username"/>
          <ErrorMssg >This username doesn't exist!</ErrorMssg>
          <Submit value="register"/>
      </FormWrapper>
)};

I tried something like this:

<FormWrapper onSubmit={handleSubmit}>

And even something like this in my Styled Components component:

const FormWrapper = styled.form.attrs({
  onSubmit:props=>props.onSubmit}`
})`
  margin: 2vw 0 0;
  display:flex;
  flex-direction:column;
  align-items:center;
`;

For now I made it work with this:

const FormWrapper = styled.div`
  form{
    margin: 2vw 0 0;
    display:flex;
    flex-direction:column;
    align-items:center;
  }
`;

const Form = () => {

  const handleSubmit = (e)=>{
    e.preventDefault();
    console.log('submitted');
  };

  return(
      <FormWrapper>
         <form autoComplete="off">
           <Input name="username" placeholder="username" autoComplete="off"/>
           <ErrorMssg >This username doesn't exist!</ErrorMssg>
           <Password name="password" placeholder="password" autoComplete="off"/>
           <ErrorMssg>The password is wrong!</ErrorMssg>
           <Submit value="log in"/>
         </form>
    </FormWrapper>
)};

Advertisement

Answer

try this

<Submit value="log in" onClick={handleSubmit}/>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement