简体   繁体   中英

How to use same page anchor tags to hide/show content in Next.js

The problem

The current project is using Next.js and this situation occurred: the content needs to be hidden or replaced, matching the current category selected. I want to do it without reloading or using another route to do so. And when the user presses F5 or reloads the page the content remains unchanged.

The attempts

Next.js' showcase page apparently is able to do so. In the docs, there's a feature called 'Shallow routing' , which basically gives the possibility to update the URL without realoading the page. That's what i figured out for now. Any clues on how the content is changed to match the category?

Thanks!

You can load the content on the client based on the category passed in the URL fragment ( # value) using window.location.hash .

Here's a minimal example of how to achieve this.

import React, { useState, useEffect } from 'react'

const data = {
    '#news': 'News Data',
    '#marketing': 'Marketing Data',
    default: "Default Data"
}

const ShowCasePage = () => {
    const router = useRouter()
    const [categoryData, setCategoryData] = useState()

    const changeCategory = (category) => {
        // Trigger fragment change to fetch the new data
        router.push(`/#${category}`, undefined, { shallow: true });
    }

    useEffect(() => {
        const someData = data[window.location.hash] ?? data.default // Retrieve data based on URL fragment
        setCategoryData(someData);
    }, [router])

    return (
        <>
            <div>Showcase Page</div>
            <button onClick={() => changeCategory('news')}>News</button>
            <button onClick={() => changeCategory('marketing')}>Marketing</button>
            <div>{categoryData}</div>
        </>
    )
}

export default ShowCasePage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM