how to add if else statements in jsx
Answered
Say's Phoebe posted this in #help-forum
Say's PhoebeOP
I want to do something like:
if current_route == "/"{
<a
href="#"
className="bg-gray-900 text-white rounded-md px-3 py-2 text-sm font-medium"
aria-current="page"
>
Home
</a>
}
else {
<a
href="#"
className="text-white rounded-md px-3 py-2 text-sm font-medium"
aria-current="page"
>
Home
</a>
}
if current_route == "/themes"{
<a
href="#"
className="bg-gray-900 text-gray-300 hover:bg-gray-700 hover:text-white rounded-md px-3 py-2 text-sm font-medium"
>
Themes
</a>
}
else{
<a
href="#"
className="text-gray-300 hover:bg-gray-700 hover:text-white rounded-md px-3 py-2 text-sm font-medium"
>
Themes
</a>
}Answered by riský
if you want inline, you can use the conditional operator: https://legacy.reactjs.org/docs/conditional-rendering.html#inline-if-else-with-conditional-operator
13 Replies
@Say's Phoebe I want to do something like:
jsx
if current_route == "/"{
<a
href="#"
className="bg-gray-900 text-white rounded-md px-3 py-2 text-sm font-medium"
aria-current="page"
>
Home
</a>
}
else {
<a
href="#"
className="text-white rounded-md px-3 py-2 text-sm font-medium"
aria-current="page"
>
Home
</a>
}
if current_route == "/themes"{
<a
href="#"
className="bg-gray-900 text-gray-300 hover:bg-gray-700 hover:text-white rounded-md px-3 py-2 text-sm font-medium"
>
Themes
</a>
}
else{
<a
href="#"
className="text-gray-300 hover:bg-gray-700 hover:text-white rounded-md px-3 py-2 text-sm font-medium"
>
Themes
</a>
}
if you want inline, you can use the conditional operator: https://legacy.reactjs.org/docs/conditional-rendering.html#inline-if-else-with-conditional-operator
Answer
@riský if you want inline, you can use the conditional operator: <https://legacy.reactjs.org/docs/conditional-rendering.html#inline-if-else-with-conditional-operator>
Say's PhoebeOP
thanks a lot, is there a possible way to know the app route like /themes in next js's layout.tsx?
as I have shown in the example current_route
make a client component which uses usePathname and import that to your layout file
Say's PhoebeOP
why is this not working?
import { useRouter } from "next/router";
const router = useRouter();
const current_route = router.pathname;use next/navigation and usePathname https://nextjs.org/docs/app/api-reference/functions/use-pathname
Say's PhoebeOP
when I have 'use client' at the top of the file, will I be able to use ssr?
yes
Say's PhoebeOP
ok, thanks alot!
@Say's Phoebe ok, thanks alot!
np, any other questions?
Say's PhoebeOP
no
yay enjoy making your app then!