I'd like to randomly generate the id
property of form inputs, to prevent them from potentially conflicting with other inputs with the same id
. This could happen if I have two login forms on the same page, each with an email
field. The reason I want/need to set the id
property is so that I can set the for
property on the label
corresponding to that input. The problem is that this randomly generated id is different on the server and the client, and so next.js throws an error. Here's some code:
function uniqueId() {
let first = (Math.random() * 46656) | 0
let second = (Math.random() * 46656) | 0
first = ('000' + first.toString(36)).slice(-3)
second = ('000' + second.toString(36)).slice(-3)
return first + second
}
const Login = () => {
const [emailId] = useState(uniqueId())
return (
<form>
<label htmlFor={emailId}>Email</label>
<input id={emailId} name='email' type='email' />
</form>
)
}
This is the error I get:
Warning: Prop 'htmlFor' did not match. Server: "email-txdmls" Client: "email-htte8e"
Any idea how to generate a random id that's consistent on the server/client? Or maybe a different way of doing it without random ids?