Reputation: 113
I am fairly new to React but was wondering if the same restrictions that apply to the regular DOM also apply to the React DOM, in this case uniqueness of HTML element IDs. I am asking because in the code I am working in at the moment I found a checkbox component that takes in an ID as a property and sets it on a child element. While this will only render one element in that actual DOM with the ID, in the React DOM there will now be two elements with the ID, the component itself will have it in addition to the child element.
const Checkbox = ({
label,
name,
id,
allowLabelHtml = false,
checked = false,
className = "checkbox-element",
onCheck = () => {},
onUncheck = () => {},
onChange = value => (value ? onCheck() : onUncheck()),
onBlur = () => {},
labelClass = ""
}) => (
<div className={className}>
<input
id={id}
name={name}
type="checkbox"
className="standard-checkbox-style"
onChange={() => onChange(!checked)}
checked={checked}
onBlur={onBlur}
/>
{label !== null && (
<label className={labelClass} htmlFor={name}>
{label}
</label>
)}
</div>
);
Also here is a screenshot of the React developer tools for chrome DOM explorer thing
Upvotes: 4
Views: 5774
Reputation: 489
In react we rarely use Ids Attributes on components. please note that either the React DOM accepts duplicate id or not,on the high level; the page would still be rendered as an html page because the browser only understands html. and the CheckBox
component might be rendered as a div
which would still have the same id as the input element.
So my advice is,
id
attribute because you want to do styling, then you should use a class
attribute.id
attribute as reference to wire-up a function onSubmit
or onChange
, then you should use a name
attribute.However i found a related post the might help you gain a better understanding through the comments.
Does the className attribute take on the role of the id attribute in Reactjs?
Upvotes: 6