im new to react so maybe i missed something. I am trying to create simple form for registration but seems like I cannot change the state.
`
import {useState} from 'react'
export const [inputs, setInputs] = useState({})
export const handleChange = (event: any) => {
const name = event.target.name
const value = event.target.value
setInputs(values => ({...values, [name]: value}))
}
export const handleSubmit = (event: any) => {
event.preventDefault()
console.log(inputs)
}
type Props = {
label: string
placeholder?: string
onChange: () => void
name?: string
value?: any
}
export const TextField = ({ label, onChange, placeholder, name, value }: Props) => {
return (
<div style={{width:'100%'}}>
<div className='text-sm my-2'>{label}</div>
<input
className='border-blue-200 border-2 rounded focus:ring-blue-200 focus:border-blue-200 focus:outline-none px-2'
style={{ height: '45px', maxWidth: '280px', width: '100%', backgroundColor: '#0D0D0D' }}
placeholder={placeholder}
onChange={onChange}
name={name}
value={value}
/>
</div>
)
}
`
and in register file i have
`
<form action="" method="post">
<div className='flex flex-col flex-wrap gap-y-5'>
<TextField name="email" value={inputs.email || ""} label='Enter Your email address:' onChange={() => {handleChange}} />
<TextField name="password" value={inputs.password || ""} label='Enter Your Password:' onChange={() => {handleChange}} />
</div>
<div className='mt-7 flex items-center gap-x-2'>
<PrimaryButton text='Register' onClick={() => {handleSubmit}} />
<div className='text-sm'>
Already Registered? <a onClick={() => push('/login')}>Login</a>
</div>
</div>
</form>
`
i am getting this error
I was just trying to get the user input from email/pass and post to postgresql db but it say cannot read state
using @sachila-ranawaka answer produces this error
CodePudding user response:
move the content inside the TextField
component and exclude the export
s
type Props = {
label: string
placeholder?: string
onChange: () => void
name?: string
value?: any
}
export const TextField = ({ label, onChange, placeholder, name, value }: Props) => {
const [inputs, setInputs] = useState({})
const handleChange = (event: any) => {
const name = event.target.name
const value = event.target.value
setInputs(values => ({...values, [name]: value}))
}
const handleSubmit = (event: any) => {
event.preventDefault()
console.log(inputs)
}
return (
<div style={{width:'100%'}}>
..........