0

I am working in Reactjs. Right now I am getting the current url/hostname. Now I want to use this URL with an if-else condition, which means I just want if url="/"(home page) then the first header should display otherwise second word should display. In other words, I want to know how we can use if-else condition with dynamic variable? Here is my current code

import { useRouter } from 'next/router'
const Header = () => {
const router = useRouter();
const url =router.asPath;


return (
    <>
    <div>
        //need to use if else condition based on "url" variable 
    </div>
   </>
    )

2 Answers 2

3

You can use ternary operators there to render based on a condition, like this:

import { useRouter } from 'next/router'
const Header = () => {
const router = useRouter();
const url = router.asPath;

return (
    <>
    <div>
        {url === "something" ? <Foo /> : <Bar />}
    </div>
   </>
    )
}
Sign up to request clarification or add additional context in comments.

2 Comments

giving me following error "ReferenceError: url is not defined"
I have updated the answer. It will work now. Issue was due to one closing braces before return statement. I just copied your code and improvised it, didn't checked the code. It came from there.
0
import { useRouter } from 'next/router'
const Header = () => {
const router = useRouter();
const url = router.asPath;

return (
    <>
    <div>
        {url === "smth" ? <First /> : <Second />}
    </div>
   </>
    )
}

return (
    <>
    <div>
        {url === "smth" && <First />}
        {url === "smth" && <Second />}
    </div>
   </>
    )
}

You use both methods

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.