1
- import React , { ChangeEvent , useState } from 'react' ;
1
+ import React , { ChangeEvent , useRef , useState } from 'react' ;
2
2
import styles from './SignUpForm.module.scss' ;
3
+ import { Form } from 'react-router-dom' ;
4
+ import { useSignUp } from '@hooks' ;
3
5
4
6
export function SignUpForm ( ) {
7
+ const { signUp } = useSignUp ( ) ;
5
8
const [ imagePreviewUrl , setImagePreviewUrl ] = useState ( '' ) ;
9
+ const [ usernameError , setUsernameError ] = useState ( '' ) ; // State for username error message
10
+ const usernameRef = useRef < HTMLInputElement | null > ( null ) ;
11
+
12
+ const handleFormSubmit = ( e : React . FormEvent ) => {
13
+ e . preventDefault ( ) ;
14
+ // You can now use the username state directly
15
+ // Accessing the username value
16
+ const username = usernameRef . current ?. value ;
17
+
18
+ if ( ! username ) {
19
+ setUsernameError ( 'Username is required' ) ; // Set error message
20
+ return ;
21
+ }
22
+
23
+ // Reset error message if username is provided
24
+ setUsernameError ( '' ) ;
25
+ signUp ( { username } ) ;
26
+ } ;
6
27
7
28
const handleImageChange = ( e : ChangeEvent < HTMLInputElement > ) => {
8
29
if ( e . target . files && e . target . files [ 0 ] ) {
@@ -15,11 +36,15 @@ export function SignUpForm() {
15
36
} ;
16
37
return (
17
38
< div className = { styles . signupFormContainer } >
18
- < form id = { styles . signupForm } >
39
+ < Form method = "POST" id = { styles . signupForm } onSubmit = { handleFormSubmit } >
19
40
< h2 > Sign Up</ h2 >
20
41
< div className = { styles . formGroup } >
21
42
< label htmlFor = "username" > Username (required)</ label >
22
- < input type = "text" id = "username" name = "username" />
43
+ < input type = "text" id = "username" name = "username" ref = { usernameRef } />
44
+ { usernameError && (
45
+ < div className = { styles . error } > { usernameError } </ div >
46
+ ) } { ' ' }
47
+ { /* Display error message */ }
23
48
</ div >
24
49
< div className = { styles . formGroup } >
25
50
< label htmlFor = "profileImage" > Profile Image (optional)</ label >
@@ -42,7 +67,7 @@ export function SignUpForm() {
42
67
) }
43
68
</ div >
44
69
< button type = "submit" > Sign Up</ button >
45
- </ form >
70
+ </ Form >
46
71
</ div >
47
72
) ;
48
73
}
0 commit comments