reactjs / react.dev

The React documentation website
https://react.dev/
Creative Commons Attribution 4.0 International
11.05k stars 7.55k forks source link

Please document how to reference a list of items #841

Open babakness opened 6 years ago

babakness commented 6 years ago

Please document how to use forwardRef (the preferred way) to retrieve a list or array of items. For example,

const foo = React.forwardRef( (props,ref) => 
  props.superHeros.map( 
    ( hero, index) => <li ref={  ref  } key={ index }>{ hero }</li>
  ) 
)

Perhaps the key question here is, why not do this?

componentDidMount(){
  const foo = this.refs.root.querySelector('.foo')
  ...
}

Suppose there are 50,000 className='foo' elements that are returned by an embedded component. Is this code not portable? Is this code slower than having 50,000 ref created?

Please document this.

danburzo commented 6 years ago

To the "why not do this" part of the question: querySelector / querySelectorAll are not live queries, so what you'd do in componentDidMount is take a snapshot of whichever .foo DOM elements exist at that particular point in time — they can, and probably will, change throughout the component's life.