Reputation: 21
I need to execute two functions in my render method by conditional checks.
Example of my code:
render() {
return (
{!this.state.isLoading && isFilled && this.state.value &&
this.renderResults()}
{!this.state.isLoading && isFilled && this.state.value &&
this.renderButton()}
)
}
I guess this is not the best way. I don't like repeating condition.
Notice I can't place one func in other one.
Upvotes: 0
Views: 632
Reputation: 7668
You can use it this way, no harm in that. Just that I see too many conditions to render in one function. But anyway, here is what you can do. And You were missing base element inside your return.
render() {
const condition = !this.state.isLoading && isFilled && this.state.value;
return (
<div>
{condition && this.renderResults()}
{condition && this.renderButton()}
</div>
)
}
Upvotes: 1
Reputation: 1482
You can do what you're trying to do here but you'll need to wrap your conditionals in an element like a <div>
or a <span>
.
render() {
return (
<div>
{!this.state.isLoading && isFilled && this.state.value &&
this.renderResults()}
{!this.state.isLoading && isFilled && this.state.value &&
this.renderButton()}
</div>
)
}
That being said, you should consider revisiting how your logic works here because each statement is the same. Without having a better idea of what you're trying to do here I would consider moving your logic to each function. This is a quick and dirty version but will give you the idea.
shouldRender() {
return !this.state.isLoading && isFilled && this.state.value
}
renderButton = () => {
if(this.shouldRender()) console.log('button')
}
renderResults = () => {
if(this.shouldRender()) console.log('results')
}
render() {
return (
<div>
{this.renderResults()}
{this.renderButton()}
</div>
)
}
Upvotes: 1
Reputation: 6919
You can wrap your both function in div. if condition fails you can return null so react doesn't render anything.
render() {
return !this.state.isLoading && isFilled && this.state.value ? (
<div>
{ this.renderResults() }
{ this.renderButton() }
</div>
) : null;
}
Upvotes: 0
Reputation: 36985
You need to wrap it in a container (such as div
or Fragment).
render() {
const shouldRender = !this.state.isLoading && isFilled && this.state.value;
return (
<div>
{shouldRender && this.renderResults()}
{shouldRender && this.renderButton()}
</div>
)
}
⚠️ I only created shouldRender
variable to make the render
more readable for demonstrative purpose only. It's not required.
Upvotes: 1