Search code examples
javascriptreactjsref

React Ref: Ref function for an array of objects only logs 1st item


I mapped through an array of objects from an external API which succesfully displays their contents. I am now trying to access their individual clientHeights through React ref but it seems to output ONLY the first item when I log to my console:


class ImageList extends React.Component{
  constructor(props){
    super(props)

    this.imageRef = React.createRef()
    
  }
  

  componentDidMount(){
    console.log(this.imageRef)
  }
  
  
  render(){

    
    const images= this.props.images.map((image)=>{
      
      return( 
          <img ref={this.imageRef}
               key={image.id} 
               src={image.urls.regular}
               alt={image.description} />
      )})
      
      
      return(
        <div  className="image-list" >
          {images}
        </div>
      
    )
    
  }
  
  
}

I'm trying to get all their clientHeights and not just the first. Thanks


Solution

  • Your code will assign each img node to this.imageRef. I'm not sure why it's keeping the first reference, but either way it won't work as you'd expect it to work. To get an array of img nodes, you need the ref to be an array and add each node to it. ref prop can be a function, so try something like this

    class ImageList extends React.Component{
      constructor(props){
        super(props)
      }
      
    
      componentDidMount(){
        console.log(this.imageRefs)
      }
      
      
      render(){
        this.imageRefs = []
        
        const images= this.props.images.map((image)=>{
          
          return( 
              <img ref={ref => {this.imageRefs.push(ref)}}
                   key={image.id} 
                   src={image.urls.regular}
                   alt={image.description} />
          )})
          
          
          return(
            <div  className="image-list" >
              {images}
            </div>
          
        )
        
      }
      
      
    }