I'm trying to add a parameter to a nextJS components which only show if a condition is true. Currently, I'm returning this:
return (
<div role="main" aria-label={this.props.title} className={Styles.main + " " + color}>
<h1>{this.props.title}</h1>
<h2>{this.props.sub}</h2>
<div className={Styles.buttons}>
<a className={Styles.button} href="#features">Features</a>
<a className={Styles.button} href="#commands">Commands</a>
<a className={Styles.button} href={this.props.inviteURL}>Invite</a>
{() => {
if (1==1) {
return (
<a className={Styles.button} href={this.props.sourceURL}>Source</a>
)
}
}}
</div>
</div>
);
Currently, it shows the top bit of the return and the buttons inside of that, but the one with the text Source
isn't shown.
Why isn't it showing, and how do I fix it?
You are using a function that is never executed, so the component will never appear, it also expects an expression, so if you use simple if
statements it won't work, as the following:
return (
<div role="main" aria-label={this.props.title} className={Styles.main + " " + color}>
<h1>{this.props.title}</h1>
<h2>{this.props.sub}</h2>
<div className={Styles.buttons}>
<a className={Styles.button} href="#features">Features</a>
<a className={Styles.button} href="#commands">Commands</a>
<a className={Styles.button} href={this.props.inviteURL}>Invite</a>
{if(1==1) {
return (
<a className={Styles.button} href={this.props.sourceURL}>Source</a>
)
}
}
</div>
</div>
);
I would suggest using ternary operators or &&
instead of an if
which leaves you the following solution:
return (
<div role="main" aria-label={this.props.title} className={Styles.main + " " + color}>
<h1>{this.props.title}</h1>
<h2>{this.props.sub}</h2>
<div className={Styles.buttons}>
<a className={Styles.button} href="#features">Features</a>
<a className={Styles.button} href="#commands">Commands</a>
<a className={Styles.button} href={this.props.inviteURL}>Invite</a>
{1==1 && <a className={Styles.button} href={this.props.sourceURL}>Source</a>}
</div>
</div>
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With