I'm trying to test a functionality out where if you have a list of li
with an attribute of aria-checked
, clicking on one will toggle it to true
, while turning the rest of the li's
aria
to false
.
I have implemented it below:
class Parent extends React.Component {
constructor(props){
super(props);
this.state = {checked: false, items:[]}
this.clicky = this.clicky.bind(this);
}
clicky(e){
this.setState({
items: [...this.state.items, e.currentTarget]
}, () => {
this.state.items.map((item, index) => {
if(index == this.state.items.length - 1){
item.setAttribute("aria-checked", "true");
}
else{
item.setAttribute("aria-checked","false");
}
})
})
}
render() {
return (
<ul>
<li
aria-checked={this.state.checked}
onClick={this.clicky}>item 1</li>
<li
aria-checked={this.state.checked}
onClick={this.clicky}>item 2</li>
<li
aria-checked={this.state.checked}
onClick={this.clicky}>item 3</li>
</ul>
)
}
}
React.render(<Parent />, document.getElementById('app'));
So on click, the clicked item's aria
will become true, while all the other once will turn false
. I'm wondering if there is a better/more efficient way of getting the same result. Thanks.
Working version: https://codepen.io/anon/pen/QmeKEw?editors=0010