1

I was reading a post titled "Change BreadCrumb component that was done with react-router v5 to react router v6"

Change BreadCrumb component that was done with react-router v5 to react router v6

Being new to react and jsx, I found the post very helpful, but I have a few questions.

This particular code snip,

{pathnames.length ? ( <Link onClick={() => navigate("/")}>Home</Link> ) : ( <Typography> Home </Typography> )}

Are the { } to indicate jsx inside the html? What is the ) : ( for?

thanks!

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Sara Banks
  • 11
  • 2
  • You're looking at the [conditional operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) which has syntax like `condition ? A : B`, which, with parentheses, looks like `condition ? (a) : (b)` Do you see the `) : (` hiding in there between the a and b now? – Wyck Dec 01 '22 at 20:15

1 Answers1

1

Are the { } to indicate jsx inside the html?

The curly brackets are what allow you to "inject" javascript into the HTML, i.e. in this case the javascript logic for using the ternary operator to conditionally render one thing or another, <div>{condition ? "this thing" : "the other thing"}</div>. {} are used when injecting values into the JSX, i.e. <div>Value: {state.value}</div>.

What is the ) : ( for?

This is part of a larger syntax, specifically ( .... ) : ( .... ) which is yet part of a larger ternary operator syntax, ... ? ( .... ) : ( .... ).

The parenthesis are mostly optional, but can help with making the code more readable (which is subjective enough already).

Compare/contrast the following examples:

{pathnames.length ? (
  <Link onClick={() => navigate("/")}>Home</Link>
) : (
  <Typography>Home</Typography>
)}
{pathnames.length ? <Link onClick={() => navigate("/")}>Home</Link> : <Typography>Home</Typography>}
{pathnames.length
  ? <Link onClick={() => navigate("/")}>Home</Link>
  : <Typography>Home</Typography>
}

All are valid and work. What formatting you choose is mostly up to you and what is easiest to read and maintain. I usually set my linters and code prettiers to auto-magically format to the first example.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • You're not wrong about the parentheses being optional, but I don't like that you used quote markdown but modified the original quote. `( .... ) : ( .... )` is not verbatim what the asker wrote. I think the whole problem was that the asker was visually parsing the `) : (` as its own entity because it was distant from the matching parentheses, and by rephrasing the question, you've avoided the origin of the misunderstanding. – Wyck Dec 01 '22 at 20:21
  • @Wyck Fair enough, that's valid point. It wasn't my intent to quote directly the OP, but rather a slightly more generalized quoted question *someone* may ask. I've edit the quote and explanation to maintain the OP's original question more accurately. – Drew Reese Dec 01 '22 at 20:32