I'm trying to render some loading elements (just empty <li>
's at this point) within a component while I wait for axios
to retrieve data from my backend. To do this I'm using a ternary operator, but for some reason I'm not getting any rendering from it - no matter if the condition is evaluates to true
or false
.
My Code
class Content extends React.Component{
constructor(){
super();
this.state = { currentItemIndex: 0 };
}
render(){
// results will either be an empty array [] or an array populated with objects
let results = this.props.results;
return <div className="content">
// note that this className will return the correct results using the same logic
<div className={(results.length ? "results" : "loading")}>
<ul>{
results.length ?
// results has data so render it all out
results.map(data => {
const index = this.state.currentItemIndex + 1;
this.setState({ currentItemIndex: index });
return <Result key={data.slug} data={data} index={index} />
}) :
// results has no data so render 8 empty list elements
new Array(8).map(() => <li></li>)
}</ul>
</div>
</div>;
}
}
So, using the above code, whether my results
array is populated or not, it will neither render the <Result />
component OR the 8 empty <li>
's like it should. Even stranger, if I change the code to something like this:
{ results.length ? "there are results" : "no results" }
It will do it just fine.
I'm fairly new to React so the problem may seem obvious, but as far as I'm aware, I'm doing everything correctly. All help is appreciated, cheers.