k buechner k buechner - 1 year ago 93
Javascript Question

Setting aria-label/aria-labelledby within React.cloneElement()?

Basically, I'm trying to clone an element and change its aria-label within React.cloneElement. I've got a component - ButtonArrows - that creates two Button components, one with an arrow icon pointing left, and one pointing right. I'd like to be able to programmatically change the aria-label, but the hyphen throws an error.

Here's some code showing what I'm trying to do:

const ButtonArrows = ({leftArrow, rightArrow, ...props})
const prevButton = (
<Button
aria-label="Previous",
icon={leftArrow}
/>
);

const nextButton = React.cloneElement(prevButton, {
//this is where the problem is:
aria-label="Next",
icon={rightArrow}
});

return(<div {...props}>{prevButton}{nextButton}</div>);
}


and obviously I can't do
aria-label="Next"
because of the hyphen.

Any suggestions? React unfortunately doesn't have anything like
htmlFor
(to stand in for
html-for
) when it comest to aria labels. Should I just put an ariaLabel prop on Button and pass it down, or is there a way to do it directly with cloneElement that I'm missing?

Answer Source

You should be able to use a plain JavaScript object here:

const nextButton = React.cloneElement(prevButton, {
  'aria-label': 'Next',
  icon: rightArrow
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download