I am searching for inline conditional solution for Href attribute in jsx. I wanted to output if i provide an url:-
<a className="navbar-brand" href="/example-url" >Logo</a>
And if not:-
<a className="navbar-brand">Logo</a>
You can include inline conditionals in your render method using a combination of the conditional ternary operator and spread attributes. For example, if the URL is a variable local to your render method, and if you only want to include the href attribute if the URL is truthy, you could do:
render() {
return (
<a className="navbar-brand" {... url ? {href: url} : {}}>Logo</a>
)
}
You could also prepare the attribute at the beginning of the render method to keep things more readable:
render() {
const attributes = url ? {href: url} : {}
return (
<a className="navbar-brand" {...attributes}>Logo</a>
)
}
If the differences between the desired elements are substantial enough, you could also alter the conditional to return different elements rather than using spread attributes. (If the ternary condition is determining the root element to be returned, you can drop the surrounding {
and }
since the compiler isn't interpreting JSX yet.)
render() {
return (
<div>
{url
? <a className="navbar-brand" href={url}>Logo</a>
: <a className="navbar-brand">Logo</a>
}
</div>
)
}
Ultimately, it depends on how much will differ between the two states and what fits the style of your codebase the best. For more information or alternatives, I'd recommend reading this related question.
try this
Above render method
let linkAttrs={}
url="/example-url"//Or empty
linkAttrs.className="navbar-brand"
if(url !=="")
linkAttrs.href=url;
In render method
<a {...linkAttrs}>Logo</a>
You could have your URL as a string in state such as
this.state = {
url: String
}
and then in your render function inside the return section, create a statement like:
{
(
this.state.url &&
<a className="navbar-brand" href={this.state.url}>Logo</a>
)
|| <a className="navbar-brand">Logo</a>
}