Automatically open the Chackra UI accordion upon page loading

Currently, I am working on developing a side menu with accordion functionality in Nextjs. I have managed to get the index values from 0 to 1 based on the page URL, but I am facing an issue where the accordion is not opening as expected. Each time a user clicks on a menu item, they are redirected to another page, which is why I want the accordion to open based on the URL.

export default function SideMenu() {
      const [accIndex, setAccIndex] = useState(0) // initially set to 0
      const router = useRouter();
      useEffect(() => {
        let url = router.pathname;
        let newUrl = url.slice(1, url.length); // remove the '/' at the beginning
        let second = newUrl.search("/"); 
        let cutUrl = second > -1 ? newUrl.slice(0, second) : newUrl;
        for (const x in Menu) {
          if (cutUrl === Menu[x].item.toLowerCase()) {
            setAccIndex(Menu[x].index); // set to 1
          }
        }
      }, []);
      
      function selectedMenu(path) {
        router.push(path);
      }

    return (
    <>
      <Accordion allowMultiple defaultIndex={[accIndex]}>
        
        {/* Dashboard */}
        <AccordionItem>
          <AccordionButton
            className="my-box"
            onClick={() => selectedMenu("/dashboard")}
          >Dashboard
          </AccordionButton>
        </AccordionItem>
        {/* Dashboard end*/}
        
        {/* About */}
        <AccordionItem>
          <AccordionButton>
            about
            <AccordionIcon />
          </AccordionButton>
          
          <AccordionPanel>
            {/* Company 1 */}
            <AccordionItem>
              <AccordionButton onClick={() => selectedMenu("/com/company1")}>
                Company 1
              </AccordionButton>
            </AccordionItem>
            {/* Company 1 end*/}
          
          </AccordionPanel>
        </AccordionItem>

     </Accordion>
     
    </>

Answer №1

Consider utilizing index as an alternative to the default index setting. It doesn't seem logical to enable allowMultiple in this case, since it would imply having multiple accordion items open but only one being reflected in the URL.

Swap out useEffect for useMemo:

      const router = useRouter();
      const index = useMemo(() => {
        //remove /
        let url = router.pathname;
        let newUrl = url.slice(1, url.length); //remove / at the beginning
        let second = newUrl.search("/");
        let cutUrl = second > -1 ? newUrl.slice(0, second) : newUrl;
        for (const x in Menu) {
          if (cutUrl === Menu[x].item.toLowerCase()) {
            return Menu[x].index; 
          }
        }
        return 0; 
      }, []);
   
      ....

      
    return (
    <>
      <Accordion index={index}>

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

Ways to terminate a running child process in npm

Within my package.json file, I have a debug script that launches a Node application. This entire NPM script is initiated by a test, and this test must terminate the debug script once it completes. When I use npm run debug and try to kill the process, the ...

Error: Collection2 validation did not pass: The field 'name' must be filled in, the field 'email' cannot be empty, and the field 'message' is mandatory

I need to set up a way for visitors to send messages through my website const mongoose = require("mongoose"); mongoose.connect("MongoDb-Connection-Uri") .then(() => { console.log("mongodb connected"); }) .catch(() => { console.log("fail ...

The time zones between Node 8 and Node 11 are not the same

Executing a basic new Date().toString() command produces different results on Node 11 compared to Node 8. In Node 11, the output includes the full timezone abbreviation like this: 'Fri May 10 2019 10:44:44 GMT-0700 (Pacific Daylight Time)' On t ...

The Drawer element is not displaying the desired styling as expected

I have a simple question about styling a Drawer component in React. When I use the sx property to add styles, they are being applied to the parent block of the Drawer instead of the Drawer itself. As a result, the styles are not appearing as expected on th ...

What is the process for combining and compressing an Angular 2 application?

I am currently trying to concatenate and minify an angular2 application. My approach so far involved concatenating all my *.js files (boot.js, application.js then all components) into one file and injecting it into my index.html. I also removed the <s ...

Discovering the Cookie in Angular 2 after it's Been Created

My setup includes two Components and one Service: Components: 1: LoginComponent 2: HeaderComponent (Shared) Service: 1: authentication.service Within the LoginComponent, I utilize the authentication.service for authentication. Upon successful authent ...

What is the most efficient method to import multiple MaterialUI components using a shared namespace without requiring the entire library to be imported

In order to prevent name mixing with other libraries, I want my MaterialUI components to be under the same namespace. For example, ensuring that <Box> references <MaterialUI.Box> and not <SomeOtherLibrary.Box>. Although it seems like a si ...

A Smarter Approach to Updating Text Dynamically with JavaScript and Vue

Currently, I am utilizing Vue to dynamically update text by using setInterval() in combination with a data property. The method I have in place is functional, but I am curious if there exists a more efficient way to optimize it. Is the current code as stre ...

Updating the DOM does not occur by simply adding an object to the Array; instead, the database is updated once the data has

My database has verified data that is being updated, however, the DOM is not reflecting these updates. <ul> <li ng-repeat="aReview in reviewList"> .... .... </li> </ul> <script> if(globalMethods.stringVa ...

Issue with Material UI: Unable to utilize import statement outside of a module due to Select dependency

Hello there! Here is my query: I am currently working on a project using NextJS + React with node. Everything seems to be running smoothly, except for one issue I encounter when reloading a page with a Select component from Material UI. The relevant code ...

Is it possible to integrate AG Grid with Redux Toolkit Query?

I am currently working on integrating AG Grid server-side model with Redux Toolkit Query. The challenge I'm facing is handling external parameters that change dynamically. With pagination, filters, and sorting enabled, I am concerned about potentiall ...

React Native ScrollView with a custom footer that adjusts its size based on the content inside (

I've implemented the code below to ensure that the blue area in image 1 remains non-scrollable when there is sufficient space, but becomes scrollable when space is limited. However, I'm facing an issue where the ScrollView component is adding ext ...

No testing detected, ending with code zero - NPM and YARN

After installing node js and yarn, I attempted to run an application/script developed by someone else. However, when running the test, I encountered the following message: No tests found, exiting with code 0 Watch Usage › Press f to run only failed tes ...

The Vue.js application is experiencing issues with displaying Google Maps functionalities

I have developed an application using Vue.js in Monaca and Cordova with onsenUI. My goal is to display my location on a Google map within the page. I attempted to achieve this by utilizing the npm package named vue2-google-maps, but unfortunately, it' ...

What is the best way to incorporate messages across various channels with a Discord bot?

While browsing through the questions of other users, I stumbled upon exactly what I was looking for. My dilemma now is how to make the same bot perform similar tasks on various channels but with different titles, footers, and so on... The primary code sni ...

What is the best way to combine Shopware 6 with Next.js as a headless service?

Can Shopware 6 be utilized as a headless service in conjunction with Nextjs? I currently use BigCommerce for my Nextjs projects, but I am interested in exploring the possibility of switching to Shopware. ...

I specialize in optimizing blog content by omitting the final line within a React framework

https://i.stack.imgur.com/WKOXT.png Currently, I have 4 lines and the 5th line in the current input field. This is my React code snippet: import { FC, useEffect, useState } from "react"; interface BlogWitterProps {} const BlogWitter: FC<B ...

How can you obtain values from a nested JSON object and combine them together?

I have a javascript object that is structured in the following format. My goal is to combine the Name and Status values for each block and then store them in an array. { "datatype": "local", "data": [ { "Name": "John", ...

Tips for creating a typescript typeguard function for function types

export const isFunction = (obj: unknown): obj is Function => obj instanceof Function; export const isString = (obj: unknown): obj is string => Object.prototype.toString.call(obj) === "[object String]"; I need to create an isFunction method ...

Enhanced customization of material-ui styles

After exploring various resources on styling overrides, I encountered a unique challenge. I am engaged in crafting styled material-ui components and integrating them across different sections of my application. My objective is to enable the customization o ...