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 use any logic and conditionals in order to build the object. You will most commonly use the ternary operator to add conditional attributes to an element in React.
We can embed any JavaScript expression in JSX by wrapping it in curly braces. But only expressions not statements, means directly we can not put any statement (if-else/switch/for) inside JSX.
This href attribute contains the URL or path to the destination page. It may be a relative URL or an absolute URL. In React, relative URLs should always be handled by the link tag provided by the React Router, and pure anchor tags should only be used for absolute paths.
Spread Operator This method is one of my favorites when it comes to conditional props. The Spread Operator is used when passing all the properties of an object or all the elements of an array to a React Component. Here, I have used the attributes object to store all the required attributes of the input field.
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.
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