0

I am learning react.js. I have an issue with a menu click on mobile.

I am displaying the Humbarger icon on the mobile. Now how can I display the close icon and menu list when the user clicks on the Humbarger icon?

The second issue is,

I am on the home page and I clicked on about us from the menu then my page is redirected to the about us but the issue is my menu is still showing open. I have to close the menu so that users can the about page.

(Step 1)

enter image description here

(Step 2)I click on Humbarger icon and menu open and I click on about us enter image description here

(Step 3) Now notice here, the page is redirect to the about us but the menu is stil open. enter image description here

You can check my code here: https://codesandbox.io/s/happy-almeida-t6q7w?file=/src/components/Header.js

Would you help me out with this issue?

user9437856
  • 2,360
  • 2
  • 33
  • 92

1 Answers1

1

What you could do is to add an event handler to the hamburger menu and close icon to update a local state like open or close. Then depending one the state you add or remove a className. Like this:

Style.css

/* When we click the hamburger menu we want to hide the icon */
.hamburger_img.close {
    display: none;
}

/* When we click the menu we want to display this icon */
.right-menu.open {
    display: block;
}

HeaderMenu.js

const HeaderMenu = () => {

    // Adding class name when scrolll
    const [openMenu, setOpenMenu] = useState(false);

    // Other code here..

    // A toggler to update the state when we open or close menu
    const toggleMenu = () => setOpenMenu(openMenu => !openMenu);

    // Dynamically add 'open' class if the state is true
    const getXMarkClassName = () => `right-menu float-right ${openMenu ? 'open': ''}`;

    // Dynamically add 'close' class if the state is true
    const getHamburgerMenuClassName = () => `hamburger_img ${openMenu ? 'close': ''}`;

    return (
        <header id="header_menu" className={headerClassName}>
            <div className={getHamburgerMenuClassName()} onClick={toggleMenu} >
                <img src={require("../images/menu.png")} alt="Menu bar"/>
            </div>
            <div className={getXMarkClassName()}>
                <div className="x_mark_img" onClick={toggleMenu} >
                     <img src={require("../images/close.png")} alt="Menu Close" />
               </div>
               <ul>
                   {/* code here... */}
               </ul>
            </div>
        </header>
  );
};

Notice that I added an onClick handler to the div to update the state whenever they are clicked. Like wise notice that I call a function to get the className for both the icon menu and the close icon.

Second Issue

To close the navigation when the route changes you can listen to route changes using useEffect and then call the toggle() function. Like this:

import React, { useEffect } from 'react';
import { useLocation } from 'react-router';

function HeaderMenu() {
    // Other code here...
    const location = useLocation();

    useEffect(() => {
      console.log("route has been changed, toggle the menu");

      if (openMenu) {
          toggleMenu();
      }

      // To scroll up on route change
      window.scrollTo(0, 0);
  }, [location.pathname]);

  // Other code here...
}

Notice I didn't add openMenu to the list of dependencies in useEffect alongside location.pathname. This is because I don't want this useEffect to run anytime the openMenu state changes only when the route changes. I have an if statement there so if the route changes and the menu wasn't opened, the toggle shouldn't be called.

Hope it helps. You can test it in this codesandbox

Tigran
  • 632
  • 1
  • 5
  • 21
rotimi-best
  • 1,852
  • 18
  • 29
  • Give me some time to check your answer – user9437856 May 06 '20 at 18:20
  • Yes, It's working perfectly for me. If possible can you help me one more issue. Like I open the menu and I click on about us. It's redirecting on about us page but notice my menu is still showing open. – user9437856 May 06 '20 at 18:36
  • okay if it worked could you mark and upvote? Send me the link, I will check it out. – rotimi-best May 06 '20 at 18:38
  • Yes, Sure, I will accept and upvote you. I am getting the issue on the same code. Do I need to ask other question? – user9437856 May 06 '20 at 18:40
  • Just update the question and explain what issue you have. I think that would be enough. – rotimi-best May 06 '20 at 18:42
  • Yes, I updated the question. Please check my second issue in the question. – user9437856 May 06 '20 at 18:52
  • I update your answer with my code, now When I refresh the page my menu showing opened. – user9437856 May 06 '20 at 19:10
  • Why you comment this if condition // if (openMenu) { toggleMenu(); // } – user9437856 May 06 '20 at 19:15
  • In the sandbox I commented the if statement in the useEffect that was why, just was testing something. Uncomment it and everything would work as expected – rotimi-best May 06 '20 at 19:16
  • Yes, I also uncomment the if condition and it's working. Thanks for the help. I am learning the react. I want to know from where you learn the react? – user9437856 May 06 '20 at 19:18
  • 1
    I learnt from watching youtube tutorials, building lots of side project and commercial ones then read the docs to get a deeper understanding. On youtube you would find enough tutorials, pick the one of your choice and start from there. All the best ;) – rotimi-best May 06 '20 at 19:21
  • 1
    Thanks for the help:) – user9437856 May 06 '20 at 19:26
  • I have noticed one issue, For example, I am on my home page and I scroll the page till the end reach(it can be any section). Then I click on about from the menu list(it can be any menu) then according to the about page should start from the hero or first section but in my scenario, it starts from the end section where I end the last page. – user9437856 May 06 '20 at 19:33
  • I see what you mean. I was able to reproduce it. What you could do is what we just did for the menu. On route change you should scroll up. Look at this answer https://stackoverflow.com/a/58156895/8817146 – rotimi-best May 07 '20 at 07:33
  • Where should I added that code? before the return ? – user9437856 May 07 '20 at 09:32
  • You should add it in the `useEffect` where we listen for route change. I updated my answer by adding this `window.scrollTo(0, 0);` and as well I updated the sandbox for you to test it out – rotimi-best May 07 '20 at 09:42
  • Oh!. Yes, it's working. Thanks for the help again. Appreciate your help and support. Do you have any link where I can learn the form validation and submit the data into database? – user9437856 May 07 '20 at 09:55
  • Yes I do. This is my best teacher so far. You can get a sense of how the frontend and backend would go together with React and Express.js (backend) https://www.youtube.com/watch?v=PBTYxXADG_k&list=PLillGF-RfqbbiTGgA77tGO426V3hRF9iE – rotimi-best May 07 '20 at 10:00
  • Thanks for the link. I'll do this form now. – user9437856 May 07 '20 at 10:05