Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix hydration error in Header.js #674

Merged
merged 6 commits into from
Oct 8, 2024

Conversation

drippypop
Copy link
Contributor

@drippypop drippypop commented Oct 4, 2024

Description:
This PR addresses the hydration error caused by text content mismatch in the server-rendered HTML in the Header.js file. The issue was due to nested <button> elements. The following changes have been made to resolve this error:

  • Removed nested <button> elements inside the NavLink component.
  • Updated the NavLink component to use the Link component properly.
  • Ensured the setOpen function is called appropriately to handle toggling the mobile navigation.

Changes:

  • Updated Header.js to remove nested <button> elements.
  • Improved the structure of the NavLink component.

File(s) Modified:

  • Website/app/Header.js

Before:

function NavLink({ to, children, cn }) {
  return (
    <Link
      scroll={false}
      href={to}
      className={`text-gray-900 hover:text-black ${cn}`}
    >
      <button>{children}</button>
    </Link>
  );
}

After:

function NavLink({ to, children, cn, setOpen }) {
  return (
    <Link
      scroll={false}
      href={to}
      className={`text-gray-900 hover:text-black ${cn}`}
      onClick={() => setOpen(false)}
    >
      {children}
    </Link>
  );
}

Testing:

  • Verified that the hydration error is resolved.
  • Tested the mobile navigation to ensure it opens and closes correctly.

Issue Fixed:

Reviewer:

  • Please review the changes and let me know if any further adjustments are needed.

Summary by CodeRabbit

  • New Features

    • Enhanced mobile navigation experience with improved link handling.
    • Navigation links now close the mobile menu upon selection.
  • Bug Fixes

    • Fixed navigation logic to ensure responsive behavior based on user actions.

Copy link

vercel bot commented Oct 4, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
drifty ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 8, 2024 2:12pm

Copy link
Contributor

coderabbitai bot commented Oct 4, 2024

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request primarily focus on enhancing the navigation functionality within the Header.js component. A new function, handleNavLinkClick, is introduced to manage navigation link interactions, allowing the mobile navigation to close when a link is clicked if the current page is already loaded. The NavLink and MobileNav components are updated to support this functionality, including passing the setOpen state to control the mobile navigation's visibility.

Changes

File Change Summary
Website/app/Header.js - Added handleNavLinkClick to manage navigation link clicks.
- Updated NavLink to use a button element and include setOpen prop.
- Modified MobileNav to accept setOpen prop for closing navigation.
- Adjusted hamburger button click handler to toggle the open state.

Assessment against linked issues

Objective Addressed Explanation
The nav bar must either close or reload the page when the same nav item is clicked again. (#673)

Possibly related PRs

Suggested reviewers

  • SaptarshiSarkar12

Poem

In the header where we roam,
A click will guide us home.
With links that close the nav with ease,
A mobile dance, a gentle breeze.
So hop along, and let us play,
Navigation's bright, come what may! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added the Website 🌐 Issues/Pull Requests regarding Website label Oct 4, 2024
Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah! You did it 🎉 Now, Relax 😉, Grab a drink ☕, and wait for the maintainers to check your contributions. Meanwhile, you can discuss on other issues and solve them 😀. Thank You 😃!

Meanwhile you can also discuss about the project in our Discord Server 😀

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
Website/app/Header.js (2)

49-51: Remove unnecessary setOpen prop from NavLink in desktop navigation

In the desktop navigation, the NavLink components are being passed setOpen={setOpen}, but the setOpen prop is primarily used for controlling the mobile navigation state. In the desktop layout, the navigation menu is always visible, and there's no need to close it.

Consider removing setOpen={setOpen} from NavLink in the desktop navigation to simplify the code.

Apply this diff:

 // In the desktop navigation at lines 154-164
 <div className="hidden md:flex mr-20 ">
-  <NavLink to="/#" cn="mx-4 flex" setOpen={setOpen}>
+  <NavLink to="/#" cn="mx-4 flex">
     HOME
   </NavLink>
-  <NavLink to="/about" cn="mx-4 flex" setOpen={setOpen}>
+  <NavLink to="/about" cn="mx-4 flex">
     ABOUT
   </NavLink>
-  <NavLink to="/download" cn="mx-4 flex" setOpen={setOpen}>
+  <NavLink to="/download" cn="mx-4 flex">
     DOWNLOAD
   </NavLink>
-  <NavLink to="/contact" cn="mx-4 flex" setOpen={setOpen}>
+  <NavLink to="/contact" cn="mx-4 flex">
     CONTACT
   </NavLink>
 </div>

Also applies to: 56-58, 63-65, 154-164


Line range hint 27-73: Simplify navigation logic by removing unnecessary functions

With the adoption of the <Link> component and client-side routing, the handleNavLinkClick function and passing setOpen to every NavLink may no longer be necessary.

Consider refactoring MobileNav and NavLink to streamline your navigation:

  • Remove the handleNavLinkClick function.
  • Pass setOpen directly to onClick handlers where needed.
  • Ensure setOpen(false) is called after navigation to close the mobile menu.

Apply this diff as a starting point:

-function handleNavLinkClick(to, setOpen) {
-  if (window.location.pathname === to) {
-    setOpen(false);
-  } else {
-    window.location.href = to;
-  }
-}
-
 function NavLink({ to, children, cn }) {
   return (
-    <button
-      onClick={() => handleNavLinkClick(to, setOpen)}
+    <Link
+      href={to}
+      onClick={() => setOpen(false)}
       className={`text-gray-900 hover:text-black ${cn}`}
     >
       {children}
-    </button>
+    </Link>
   );
 }

Ensure that setOpen(false) is called appropriately to close the mobile navigation after a link is clicked.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 99e427a and d9a158a.

📒 Files selected for processing (1)
  • Website/app/Header.js (4 hunks)

Website/app/Header.js Show resolved Hide resolved
@SaptarshiSarkar12
Copy link
Owner

@drippypop Awesome work 👏.
I have verified it works.
What do you think of this review - #674 (comment)?

@SaptarshiSarkar12 SaptarshiSarkar12 added the bug 🐛 Issues/Pull Requests reporting/fixing a bug label Oct 4, 2024
@drippypop
Copy link
Contributor Author

@SaptarshiSarkar12 fixing it right now

Website/app/Header.js Fixed Show fixed Hide fixed
Website/app/Header.js Fixed Show fixed Hide fixed
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (3)
Website/app/Header.js (3)

156-166: LGTM: Header component changes with minor suggestion

The modifications to the Header component, including passing setOpen to MobileNav and each NavLink, are consistent with the changes made to other components. This implementation effectively addresses the issue of the navigation bar not closing when a link is clicked.

For consistency, consider updating the "HOME" NavLink to use a lowercase path:

-          <NavLink to="/#" cn="mx-4 flex" setOpen={setOpen}>
+          <NavLink to="/" cn="mx-4 flex" setOpen={setOpen}>

This change aligns with the path format used in other NavLink components and removes the unnecessary hash.


Line range hint 137-139: Use functional update for setOpen

The current implementation directly toggles the open state. For consistency and to avoid potential issues with state updates, it's recommended to use the functional form of setOpen.

Update the click handler as follows:

-          onClick={() => {
-            setOpen(!open);
-          }}
+          onClick={() => setOpen(prevOpen => !prevOpen)}

This change ensures that the state update is based on the previous state, which is a more reliable approach, especially when dealing with asynchronous state updates.


Line range hint 1-187: Overall good implementation with suggestions for improvement

The changes in this file effectively address the hydration error and the issue of the navigation bar not closing when clicking on the current page. The implementation of handleNavLinkClick and the modifications to NavLink, MobileNav, and Header components work together to solve the described problems.

To further improve the code quality and consistency:

  1. Consider using a linter (e.g., ESLint) with a consistent configuration to standardize code style, including quotation marks usage.
  2. Implement the suggestions provided in the previous comments, particularly:
    • Updating the router import for the Next.js App Router
    • Refactoring handleNavLinkClick for better Next.js integration
    • Preserving the Link component in NavLink for SEO and accessibility
    • Using a functional update for setOpen in the hamburger button click handler

These changes will enhance the overall quality, maintainability, and performance of the component.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between d9a158a and 6498e9f.

📒 Files selected for processing (1)
  • Website/app/Header.js (4 hunks)
🔇 Additional comments (1)
Website/app/Header.js (1)

29-29: LGTM: MobileNav changes

The modifications to the MobileNav component, including passing the setOpen prop to each NavLink, effectively address the issue of the navigation bar not closing when a link is clicked. This implementation aligns well with the PR objectives.

Also applies to: 51-51, 58-58, 65-65

Website/app/Header.js Outdated Show resolved Hide resolved
@SaptarshiSarkar12
Copy link
Owner

@drippypop Please fix the reviews and errors by GitHub Advanced Security bot and Coderabbit AI bot.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (2)
Website/app/Header.js (2)

155-165: LGTM with suggestion: NavLink updates in main navigation

The addition of the setOpen prop to the NavLink components in the main navigation is consistent with the earlier changes and improves functionality.

However, consider optimizing this for desktop views:

  1. You could conditionally pass the setOpen prop based on the viewport size:
const isMobile = useMediaQuery('(max-width: 768px)');

// In the JSX
<NavLink 
  to="/#" 
  cn="mx-4 flex" 
  setOpen={isMobile ? setOpen : undefined}
>
  HOME
</NavLink>
// Repeat for other NavLinks

This would prevent unnecessary state updates on desktop views where the mobile navigation isn't used.


13-13: Ensure router is defined before accessing

While the static analysis tool flags a potential issue with router.push(to), this is likely a false positive given the context. However, it's always good to add a safety check.

Consider adding a null check before using the router:

if (router && typeof router.push === 'function') {
  router.push(to);
} else {
  // Fallback behavior, e.g., using window.location
  window.location.href = to;
}

This will make the code more robust and prevent potential runtime errors if router is unexpectedly undefined.

🧰 Tools
🪛 GitHub Check: CodeQL

[failure] 13-13: Property access on null or undefined
The base expression of this property access is always undefined.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 6498e9f and 6b8d6f9.

📒 Files selected for processing (1)
  • Website/app/Header.js (4 hunks)
🧰 Additional context used
🪛 GitHub Check: CodeQL
Website/app/Header.js

[notice] 7-7: Unused variable, import, function or class
Unused import useRouter.


[failure] 13-13: Property access on null or undefined
The base expression of this property access is always undefined.

🔇 Additional comments (2)
Website/app/Header.js (2)

28-28: LGTM: MobileNav prop update

The addition of the setOpen prop to the MobileNav component is a good change. It allows the component to control the mobile navigation state, which is consistent with the modifications made to the NavLink component.


50-50: LGTM: NavLink updates in MobileNav

The addition of the setOpen prop to the NavLink components within MobileNav is correct and consistent with the earlier changes. This modification ensures that the mobile navigation closes when a link is clicked, improving the user experience.

Also applies to: 57-57, 64-64

Website/app/Header.js Outdated Show resolved Hide resolved
Website/app/Header.js Show resolved Hide resolved
Website/app/Header.js Outdated Show resolved Hide resolved
@drippypop
Copy link
Contributor Author

gosh.. what's going on lol

Copy link
Contributor Author

@drippypop drippypop left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

conversations are still there

@drippypop
Copy link
Contributor Author

@SaptarshiSarkar12 FINALLY fixed it!

Copy link
Owner

@SaptarshiSarkar12 SaptarshiSarkar12 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@drippypop The fix no longer works 😞. Please check and make the necessary changes. Probably router doesn't work as expected.

@SaptarshiSarkar12
Copy link
Owner

@drippypop As the recent fixes don't work as expected, you can revert to commit d9a158a
I would accept that change 😁.

@drippypop
Copy link
Contributor Author

@SaptarshiSarkar12 sorry about that! I'll make sure to revert to that

@SaptarshiSarkar12
Copy link
Owner

@drippypop Great 😃👍

Copy link
Owner

@SaptarshiSarkar12 SaptarshiSarkar12 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@drippypop Looks good to merge 👍.
Thanks for contributing 🚀 🚀.
You may join our Discord server - https://discord.gg/DeT4jXPfkG to get updates about the project.

@SaptarshiSarkar12 SaptarshiSarkar12 merged commit d4d5f4b into SaptarshiSarkar12:master Oct 8, 2024
11 checks passed
@SaptarshiSarkar12 SaptarshiSarkar12 added the hacktoberfest-accepted Accepted Pull Requests for Hacktoberfest label Oct 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug 🐛 Issues/Pull Requests reporting/fixing a bug hacktoberfest-accepted Accepted Pull Requests for Hacktoberfest Website 🌐 Issues/Pull Requests regarding Website
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[BUG] The nav bar does not close if the selected nav item is already loaded
2 participants