Reputation: 18592
I have this situation where I need to store reference of components in array.
when the render method called I clear the array by this code :
this.arr = [];
and then use ref
to push the components I need to the array using this code:
<span ref={ref => this.arr.push(ref)} />
the problem is that in first render the array have all the two components , but in the later renders the array returns all components but with two other null
s.
Checkout this example :
class Test extends React.Component
{
constructor(props)
{
super(props);
this.state = {value: 0};
this.arr = [];
}
render()
{
this.arr = [];
return (
<div>
<span ref={ref => this.arr.push(ref)}>Span 1/</span>
<span ref={ref => this.arr.push(ref)}>Span 2</span>
<br/>
<b>Array Length = {this.state.value}</b>
<button onClick={this.onClick}>GET LENGTH</button>
</div>
);
}
onClick = () =>
{
console.log(this.arr);
this.setState({value: this.arr.length});
}
}
ReactDOM.render( <Test></Test> , document.getElementById('root'));
<html>
<head>
<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>
</head>
<body>
<div id="root"></div>
</body>
</html>
Can any one explain why I get this behavior and why the array not cleared after setting it to []
, and how could I solve this problem
Upvotes: 0
Views: 75
Reputation: 19690
because x
in "ref"={x => ...}
can and will be null
at first call and then will be the refernce to you component when react calls it the second time, so if you don't want null
's in your array you need to guard check x
for null before storing it
Upvotes: 1
Reputation: 33974
You can do something like below by managing in state
class Test extends React.Component
{
constructor(props)
{
super(props);
this.state = {value: 0, arr: []};
}
pushToRef = (ref) => {
if(ref != null){
this.setState(prevState => ({
arr: [...prevState.arr, ref]
}));
}
}
render()
{
return (
<div>
<span ref={ref => this.pushToRef(ref)}>Span 1/</span>
<span ref={ref => this.pushToRef(ref)}>Span 2</span>
<br/>
<b>Array Length = {this.state.value}</b>
<button onClick={this.onClick}>GET LENGTH</button>
</div>
);
}
onClick = () =>
{
console.log(this.state.arr);
this.setState({value: this.state.arr.length});
}
}
ReactDOM.render( <Test></Test> , document.getElementById('root'));
you can empty the state wherever required except render. Something like below
let arr = [];
thi.setState({
arr: arr
});
Upvotes: 1
Reputation: 187
Try
this.arr.length = 0;
You are reinitializing the variable to a new empty array instance.
Not too familiar with React but my guess is that the instance of the array that the view is referencing is lost as soon as you set the array equal to a new array instance;
Upvotes: 1