Using single page anchor tags in Next.js to toggle content visibility

The Issue

Currently working on a project using Next.js and facing a challenge: needing to hide or replace content based on the selected category without reloading the page or navigating to another route. Furthermore, ensuring that when the page is reloaded (e.g. by pressing F5), the content remains unaffected.

Exploring Solutions

Upon exploring Next.js' showcase page, it seems possible through a feature called 'Shallow routing'. This allows for updating the URL without forcing a full reload of the page. This is what I have gathered so far. Any insights on how to dynamically update content based on category selection would be greatly appreciated!

Thank you in advance!

Answer №1

To dynamically load content on the client based on the category provided in the URL fragment (# value), you can utilize the window.location.hash property.

Below is a simple example demonstrating how this can be implemented:

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

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

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

    const changeCategory = (category) => {
        // Update URL fragment to trigger data fetching
        router.push(`/#${category}`, undefined, { shallow: true });
    }

    useEffect(() => {
        const someData = data[window.location.hash] ?? data.default // Retrieve content 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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Troubleshooting the ineffectiveness of JavaScript's

(After reviewing all questions and answers related to this issue, I have not found a solution that works for me.) Here is the code snippet in question: var timeoutHandle; function showLoader(show) { if (show) { $('.loader').html(&a ...

Triggering a JavaScript function when a page is focused due to user interaction

In my project, I have a specific requirement that involves triggering a new window to open when the user clicks on an icon. In this new window, the user should be able to view and edit certain fields. Upon closing the new window and returning to the parent ...

Discovering objects on a JavaScript webpage using Selenium

Looking to automate some searches for myself, but running into an issue. Here is the website in question: Struggling to locate the search bar using the program, and unsure why. driver = webdriver.Firefox() driver.get('https://shop.orgatop.de/') ...

Assign a value to the cookie based on the input from the form

I recently asked a similar question, but it seems like I missed providing some context, which is why I couldn't get it to work. My goal is to set a cookie value of a form entry when clicking on it (using the carhartl jquery plugin), but nothing happen ...

Obtain the dimensions (width and height) of a collection of images using Angular and TypeScript

Currently, I am facing an issue with my image upload functionality. My goal is to retrieve the width and height of each image before uploading them. However, I've encountered a problem where my function only provides the dimensions for the first image ...

Utilizing React JS Styled-Components to Import Images from the Public Directory

I've been attempting to set the image as a background-image from the public folder using styled-components. I've tried the following: import styled from "styled-components"; import Background from 'process.env.PUBLIC_URL + /images/ ...

saving user information with asynchronous HTTP calls

I am encountering an issue while trying to save my form data using AJAX. When I submit the form data in a JavaScript file that calls another PHP file to perform an insertion operation, an error occurs. Here is the code snippet: <button id="submit" cl ...

React-app size has grown larger post-deployment

I recently created my second app clone using React. I have noticed that after deployment, the size of the app increases. Everything looks normal on localhost:3000, but it significantly grows once deployed. Any assistance in resolving this issue would be gr ...

SQL stores Array Input as a static identifier 'Array'

Previously, I was able to save an object in the database. However, now I need to save each individual data in an array within a row. I attempted to use array_column to store a specific set of data in a column, but it ended up saving as the word 'Array ...

Initialize an array in React state using an initialization function that continuously updates the state using setState

I'm trying to initialize a state array by calling an init function multiple times in the useEffect hook. // id for new Users const [id, setId] = useState(0); // users list const [users, setUsers] = useState([]); function createUser() { const newUse ...

Tips for verifying that input is provided in a text field when the checkbox is marked

Can someone help me with validating a form where the user must enter data in a text field if they check a checkbox? I have JavaScript code for checkbox validation, but need assistance with text field validation. Thank you! $(document).ready(function () ...

Receiving a reply from the axios function

Whenever I try to call the lookUpItem function from ItemSearch.vue, I always get an undefined response. Code snippet from ItemSearch.vue: <script setup lang="ts"> import { lookUpItem } from '../systemApi' async fu ...

When attempting to install the necessary react JSX dependencies, the npm installation process encounters

The information I have on this topic may be somewhat indirect I've developed an electron application using react, but without utilizing create-react-app There's no turning back now, so my goal is to add development dependencies for working with ...

Update all field values in Redux-form version 6.0 and above

I am attempting to update several values in redux-form. They are stored in a single object, and I want to replace the current redux-form state values with those from my object. One method I have tried involves using this.props.reset() followed by multipl ...

Is there a way to rigorously validate my HTML, CSS, and JavaScript files against specific standards?

Can modern browsers suppress errors in HTML, CSS, and JS sources? Is there a method to uncover all mistakes, no matter how small they may be? ...

Incorporating multiple CSS style sheets within a single HTML document

As part of my assignment, I have successfully created two different CSS style sheets. The next step is to link both style sheets to a single HTML page and provide users with the option to switch between the two styles. I am wondering how to achieve this. ...

Error message in Typescript: When a class has initialized properties, a 'super' call must be the first statement in the constructor

I am currently facing some typescript errors in my project. Would you like to see a sample of the code that is causing the issue? Here is a snippet: module CoreWeb { export class Controller implements IController { public $q; ... This piece of cod ...

What is the best approach to transforming my jQuery function into CSS to ensure responsiveness?

I have created a jQuery animation with four functions named ani1(), ani2(), ani3(), and ani4(). Everything is working fine on desktop, but now I am facing the challenge of making it responsive for mobile devices. I am looking for CSS code to replicate the ...

What is the reason for sending a single file to the server?

A function called "import File" was developed to send multiple files to the server, but only one file is being received. Input: <input type="files" id="files" name="files" multiple onChange={ (e) => this.importFile(e.target.files) } ...

What is the best way to incorporate a toggle feature for multiple elements in ReactJS so that clicking on an element displays a menu, and clicking outside of the menu hides

Looking for a way to create multiple toggle functionalities in ReactJS on a single page? When clicking on different elements, you want specific menus to reveal and hide when clicked outside of the menu? I have successfully implemented a toggle function fo ...