2

I am working on Reactjs and using nextjs framework,Right now i want if url containing "?id=pinned" then different text should display,How can i do this ? Here is my current code in [slug.js]

return(
        if(url containing pinned)
        {
            <div id="neww" className="neww"><h3>Pinned</h3></div>
        }
        else
        {
         <div id="neww" className="neww"><h3>Newest</h3></div>
        }
)

5 Answers 5

1

Since it seems like you're using Next.js, you can use Next.js API to do this

import { useRouter } from 'next/router'

const Post = () => {
  const router = useRouter()
  const { id } = router.query
  const isPinned = id === 'pinned'
  
  if (isPinned) {
     return (<div id="neww" className="neww"><h3>Pinned</h3></div>)
  } else {
     return (<div id="neww" className="neww"><h3>Newest</h3></div>)
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Do this:

import { useRouter } from 'next/router'

const Post = () => {
  const {query} = useRouter()
  const isPinned = query.id === 'pinned'
  return (<div id="neww" className="neww">
           <h3>{isPinned ? 'Pinned': 'Newest'}</h3>
         </div>)
}

Comments

0

ignore if else, you should try the ternary operator

return(
        <div id="neww" className="neww">
          <h3> 
            {(url.includes('pinned') ? "Pinned":"Newest" }                         
          </h3>
       </div>
)

2 Comments

i am getting error "url is not defined"
is URL variable ? or are you referring document.URL?
0

You can use the query from router

Example

const router = useRouter();
const {id} = router.query;


return(
        if(id === "pinned")
        {
            <div id="neww" className="neww"><h3>Pinned</h3></div>
        }
        else
        {
         <div id="neww" className="neww"><h3>Newest</h3></div>
        }
)

Comments

0

Here is a way:

import { useRouter } from "next/router";

  const router = useRouter();
  const id = router.query["id"];
  return(
        if(id === "pinned")
        {
            <div id="neww" className="neww"><h3>Pinned</h3></div>
        }
        else
        {
         <div id="neww" className="neww"><h3>Newest</h3></div>
        }
)

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.