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:
JavaScript
x
7
1
const FormWrapper = styled.form`
2
margin: 2vw 0 0;
3
display:flex;
4
flex-direction:column;
5
align-items:center;
6
`;
7
My react parent component:
JavaScript
1
15
15
1
const Form = () => {
2
3
const handleSubmit = (e)=>{
4
e.preventDefault();
5
console.log('submitted');
6
};
7
8
return(
9
<FormWrapper>
10
<Input name="username" placeholder="username"/>
11
<ErrorMssg >This username doesn't exist!</ErrorMssg>
12
<Submit value="register"/>
13
</FormWrapper>
14
)};
15
I tried something like this:
JavaScript
1
2
1
<FormWrapper onSubmit={handleSubmit}>
2
And even something like this in my Styled Components component:
JavaScript
1
9
1
const FormWrapper = styled.form.attrs({
2
onSubmit:props=>props.onSubmit}`
3
})`
4
margin: 2vw 0 0;
5
display:flex;
6
flex-direction:column;
7
align-items:center;
8
`;
9
For now I made it work with this:
JavaScript
1
28
28
1
const FormWrapper = styled.div`
2
form{
3
margin: 2vw 0 0;
4
display:flex;
5
flex-direction:column;
6
align-items:center;
7
}
8
`;
9
10
const Form = () => {
11
12
const handleSubmit = (e)=>{
13
e.preventDefault();
14
console.log('submitted');
15
};
16
17
return(
18
<FormWrapper>
19
<form autoComplete="off">
20
<Input name="username" placeholder="username" autoComplete="off"/>
21
<ErrorMssg >This username doesn't exist!</ErrorMssg>
22
<Password name="password" placeholder="password" autoComplete="off"/>
23
<ErrorMssg>The password is wrong!</ErrorMssg>
24
<Submit value="log in"/>
25
</form>
26
</FormWrapper>
27
)};
28
Advertisement
Answer
try this
JavaScript
1
2
1
<Submit value="log in" onClick={handleSubmit}/>
2