I'm constructing an element with an unknown number of children using React and I need a reference to each. Consider the following code:
class Items extends React.Component {
constructor() {
super();
this.itemEls = [];
}
render() {
return (
<div>
{
this.props.items.map((item, index) => {
return <div className="item" key={index} ref={(el) => this.itemEls.push(el)}>{item}</div>;
})
}
</div>
);
}
componentDidMount() {
console.log(this.itemEls.map((el) => el.innerHTML));
}
}
ReactDOM.render(<Items items={["Hello", "World", "Foo", "Bar"]} />, document.getElementById('container'));
.item {
display: inline-block;
background: #EEE;
border: 1px solid #DDD;
color: #999;
padding: 10px;
font-family: sans-serif;
font-weight: bold;
margin: 10px;
border-radius: 5px;
cursor: default;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
I loop through the provided array and save a reference to each element as I go. When the component mounts, I print out a list of the element contents in the order they were added to the array. So far in all of my testing the order has been correct, but I can't find any documentation that confirms that this isn't just the most common result of a secret race condition going on in the background.
Is the order in which reference functions are called consistent?
The obvious solution here would be to pre-set the array length in componentWillMount
and populate it with the index
value from this.props.items.map
- but for the sake of argument, let's say that's not possible in the actual situation I find myself in.