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>
}
)
CodePudding user response:
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>)
}
}
CodePudding user response:
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>)
}
CodePudding user response:
ignore if else, you should try the ternary operator
return(
<div id="neww" className="neww">
<h3>
{(url.includes('pinned') ? "Pinned":"Newest" }
</h3>
</div>
)
CodePudding user response:
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>
}
)
CodePudding user response:
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>
}
)