Deke
Deke

Reputation: 4649

How to iterate over DOM?

How to iterate over DOM element inputbox. I want to loop through each <input/>. I get error this.refs.inputBoxes.map is not a function

componentDidMount: function(){
  this.refs.inputBoxes.map(function(e, i){
  console.log(e)
})



render: function () {
  return (
    <div>
      <input className= "iB" type="checkbox" ref="inputBoxes"/> 
      <input className= "iB" type="checkbox" ref="inputBoxes"/>
      <input className= "iB" type="checkbox" ref="inputBoxes"/>
    </div>
  )
}

Upvotes: 0

Views: 993

Answers (2)

Jack
Jack

Reputation: 21163

There's really no reason to not just use document.querySelectorAll

componentDidMount: function() {
  var inputs = document.querySelectorAll('input.iB');
  for (var i = 0; i < inputs.length; i++) {
    console.log(inputs[i]);
  }
}


render: function () {
  return (
    <div>
      <input className= "iB" type="checkbox" ref="inputBoxes"/> 
      <input className= "iB" type="checkbox" ref="inputBoxes"/>
      <input className= "iB" type="checkbox" ref="inputBoxes"/>
    </div>
  )
}

Upvotes: -1

Bal&#225;zs &#201;des
Bal&#225;zs &#201;des

Reputation: 13807

I think you are simply overriding the previously set this.refs.inputBoxes field. I don't think that automatically becomes an array if you set the same ref for multiple components. However you could give a ref to your container:

<div ref={e => this._inputBoxContainer = e}>
  <input className= "iB" type="checkbox"/> 
  <input className= "iB" type="checkbox"/>
  <input className= "iB" type="checkbox"/>
</div>

And in your mount method simply access the children! If you want to perform array operations on it you will have to convert it to an array since it's an HtmlCollection.:

componentDidMount() {
  Array.from(this._inputBoxContainer.children).map(e => {
    console.log(e)
  })
}

Upvotes: 4

Related Questions