screen_rotation
Copied to Clipboard
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script> </head> <body> <div id="app"></div> <script type="text/babel"> const { useState, useRef } = React; function App() { const [otpValues, setOtpValues] = useState(['', '', '', '']); const otpFieldsRef = useRef([]); const handleInput = (index, value) => { if (value.length > 1) { return; } const newOtpValues = [...otpValues]; newOtpValues[index] = value; setOtpValues(newOtpValues); if (value.length === 1 && index < otpValues.length - 1) { otpFieldsRef.current[index + 1].focus(); } }; const handleBackspace = (index) => { if (otpValues[index] !== '') { const newOtpValues = [...otpValues]; newOtpValues[index] = ''; setOtpValues(newOtpValues); } else if (index > 0) { otpFieldsRef.current[index - 1].focus(); } }; return ( <div className='container'> <h3>React Js OTP Input Example</h3> <div className="otp-container"> {otpValues.map((value, index) => ( <input key={index} type="text" maxLength="1" className="otp-input" value={value} onChange={(e) => handleInput(index, e.target.value)} onKeyDown={(e) => { if (e.key === 'Backspace') { handleBackspace(index); } }} ref={(ref) => { otpFieldsRef.current[index] = ref; }} /> ))} </div> </div> ); } ReactDOM.render(<App />, document.getElementById("app")); </script> <style> * { box-sizing: border-box; } body { font-family: Arial, sans-serif; margin: 0; padding: 0; } .container { margin: 0 auto; width: 600px; box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.12), 0 2px 4px 0 rgba(0, 0, 0, 0.24); padding: 20px; display: flex; align-items: center; flex-direction: column } .otp-container { display: flex; } .otp-input { width: 40px; height: 40px; margin: 0 5px; border: 2px solid #ccc; border-radius: 5px; font-size: 24px; text-align: center; outline: none; } .otp-input:focus { border-color: #007bff; } /* Optional: To add more styling for completed inputs */ .otp-input.completed { border-color: #28a745; } </style> </body> </html>