The HTML <label> or label tag in HTML defines a label for the <input> element. Such as textbox, email, password, and textarea… Setting the `for` attribute on a Label element in React is slightly different.
Set the `for` attribute on a Label element in React
Switch for
becomes htmlFor
Usually, labels are bound to input text using the id attribute.
<div id = "root"> <div> <label for = "email">Email</label> <input type = "text" id = "email" name = "email" size = "30" /> <div> <div>
But if you use it in React, it gives the following warning:
app.js:21988 Warning: Invalid DOM property `for`. Did you mean `htmlFor`?
To prevent that from happening is very simple; you just need to change the for to htmlFor
.
<div id = "root"> <div> <label htmlFor = "email">Email</label> <input type = "text" id = "email" name = "email" size = "30" /> <div> <div>
Make sure to write the correct syntax if you don’t want any silly mistakes because React is case-sensitive.
Use DOM
Still using htmlFor
but we will combine it with DOM to change the value of the attribute of a label:
document.getElementById("labelName").htmlFor = "newLabel";
This is a rarely used method, but it will still be useful when you want to add new functionality to the web.
Summary
This article has covered some basic methods to set the `for` attribute on a Label element in React with some simple examples. Hope this post will be useful to you.
If you have any questions, please leave a comment.
After studying and researching, I have acquired the necessary programming skills of a web programmer. In addition to HTML, Css, Bootstrap has some popular libraries such as reactJS and NodeJS. It is enough for me when designing from front-end to back-end.