I am having an issue trying to figure out how to paste a value into multiple input fields. I am basically building a verify screen with 6 separate inputs that have a maxLength of 1, and want to be able to paste the entire 6 digit code so that is populates all 6 inputs. I have found several solutions in Jquery but not quite sure how to pull it off in react. Here is my code.
const Verify = ({ handleSubmit, method, rec, changeInput }) => {
const navigate = useNavigate();
const { email, phone } = rec
const send = method === 'email' ? { email: email } : { phone: phone }
const renderContent = () => {
const methodLabel = method === 'email' ? 'email address' : 'phone number'
return (
<>
<div id="back-grad"/>
<div className="col-md-8">
<div className='verify-text-section'>
<p className="verify-text pb-5">
Enter the PIN number we just sent to your {methodLabel}.
</p>
</div>
<div className="flex">
<input name='code-1' className='code-input mr-2' autoFocus maxLength='1' onChange={changeInput} />
<input name='code-2' className='code-input mr-2' maxLength='1' onChange={changeInput} />
<input name='code-3' className='code-input mr-2' maxLength='1' onChange={changeInput} />
<input name='code-4' className='code-input mr-2' maxLength='1' onChange={changeInput} />
<input name='code-5' className='code-input mr-2' maxLength='1' onChange={changeInput} />
<input name='code-6' className='code-input mr-2' maxLength='1' onChange={changeInput} />
</div>
<div className="verify-resend mt-3" onClick={resendPin}>Resend Code</div>
<div className="flex margin-set text-center">
<button className="btn btn-block text-white verify-btn">
<p className="verify-btn-text">VERIFY</p>
</button>
</div>
</div>
</>
)
}
return (
<>
{rec.email.length < 1 && rec.phone.length < 1 ? <Navigate to={'/auth'} />
:
<div className="d-flex align-items-center h-full">
<form className="container" onSubmit={e => onFormSubmit(e, handleSubmit)}>
<div className="row justify-content-center">
{renderContent()}
</div>
</form>
</div>
}
</>
)
}
and here is the changeInput function and handleChange function, as well as what rec looks like being passed to the component.
const [rec, setRec] = useState({
accept: false,
email: '',
phone: '',
pin: [],
})
const changeInput = (e) => {
const { maxLength, name, value } = e.target;
const [fieldName, fieldIndex] = name.split('-')
if(value.length >= maxLength) {
if(parseInt(fieldIndex, 10) < numOfFields) {
const nextSibling = document.querySelector(`input[name=${fieldName}-${parseInt(fieldIndex, 10) + 1}]`)
if(nextSibling !== null) {
nextSibling.focus()
}
}
setRec({
...rec,
pin:[...rec.pin, value]
})
}
}
const handleChange = (name, value) => {
if (name === 'mobile') name = 'phone'
const recState = {
...rec,
[name]: value,
}
setRec(recState)
}
any help would be appreciated.