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: div-in-p issue in tooltip #4053

Open
wants to merge 1 commit into
base: canary
Choose a base branch
from

Conversation

rishabhverma54321
Copy link

@rishabhverma54321 rishabhverma54321 commented Nov 14, 2024

Closes #

📝 Description

This PR adds support for using React lazy or server components inside a Tooltip component

⛳️ Current behavior (updates)

Currently, in Next 14 and above, passing a lazy or server component inside a tooltip results in an error.
In HTML, <div> cannot be a descendant of <p>. This will cause a hydration error.

🚀 New behavior

A new check has been added to render lazy and server components in a div instead of a p tag to prevent hydration issues.

💣 Is this a breaking change (Yes/No):

No - This condition will only work with lazy and server components.

📝 Additional Information

Summary by CodeRabbit

  • New Features

    • Enhanced Tooltip component to support lazy-loaded React elements.
    • Improved validation for the children prop to ensure it is a valid React element or a lazy element.
  • Bug Fixes

    • Added error handling for invalid children, defaulting to a <p> element when necessary.
  • Documentation

    • Updated type definitions and utility functions for better clarity and usability.

Copy link

vercel bot commented Nov 14, 2024

@rishabhverma54321 is attempting to deploy a commit to the NextUI Inc Team on Vercel.

A member of the Team first needs to authorize it.

Copy link

changeset-bot bot commented Nov 14, 2024

⚠️ No Changeset found

Latest commit: e948c45

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Nov 14, 2024

Walkthrough

The changes in this pull request enhance the Tooltip component by introducing support for lazy-loaded React elements. A new utility function, isLazyElement, is added to validate the children prop, ensuring it is either a valid React element or a lazy element. If validation fails, a default <p> element is rendered. The use-tooltip.ts file is also updated to include a new type alias, LazyElement, and the corresponding function to check for lazy elements. Overall, these modifications improve the flexibility and robustness of the tooltip's child element handling.

Changes

File Path Change Summary
packages/components/tooltip/src/tooltip.tsx - Imported isLazyElement from ./use-tooltip.
- Updated children prop validation logic.
- Default rendering behavior modified for invalid children.
packages/components/tooltip/src/use-tooltip.ts - Added type alias LazyElement.
- Implemented isLazyElement function to check for lazy elements.
- Updated React import to include ReactElement.

Possibly related issues

  • [BUG] - div-in-p issue in tooltip #3975: The changes address a div-in-p hydration issue by ensuring that the children prop is validated correctly, potentially preventing hydration errors in server components.

Suggested reviewers

  • jrgarciadev
  • wingkwong

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.

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.

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)
packages/components/tooltip/src/tooltip.tsx (1)

46-47: Consider adding ARIA attributes for better accessibility

While the div wrapper solves the hydration issue, consider adding appropriate ARIA attributes to maintain semantic meaning, especially since we're using a generic div container.

-      trigger = <div {...getTriggerProps()}>{children}</div>;
+      trigger = <div {...getTriggerProps()} role="tooltip" aria-label="tooltip content">{children}</div>;
packages/components/tooltip/src/use-tooltip.ts (1)

94-94: Consider narrowing the LazyElement type definition

The current type definition includes null and undefined, which might be too permissive for lazy elements. Consider if these should be handled separately to make the type more precise.

-export type LazyElement = ReactElement | ReactNode | null | undefined;
+export type LazyElement = ReactElement | ReactNode;
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c6326d1 and e948c45.

📒 Files selected for processing (2)
  • packages/components/tooltip/src/tooltip.tsx (2 hunks)
  • packages/components/tooltip/src/use-tooltip.ts (3 hunks)
🔇 Additional comments (4)
packages/components/tooltip/src/tooltip.tsx (2)

10-10: LGTM: Import change aligns with new functionality

The addition of isLazyElement import is necessary for the new lazy element detection feature.


44-47: Implementation correctly addresses hydration issues

The changes effectively solve the div-in-p hydration error by:

  1. Adding a check for lazy elements
  2. Using appropriate container elements (div for lazy components, p for text)

Let's verify the styling consistency:

✅ Verification successful

Implementation is safe and styling is properly handled

After reviewing the implementation, the change to use a div wrapper for lazy elements is safe because:

  1. Styling is handled through the getTriggerProps() which applies consistent classes and attributes
  2. The tooltip uses a slot-based styling system that's independent of the trigger element type
  3. The trigger wrapper (p or div) inherits the same props and styling mechanism regardless of the element type
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for any existing tooltip-specific CSS that might be affected by the div wrapper
rg -g '*.{css,scss}' 'tooltip'

# Look for potential style overrides that might affect the new div wrapper
ast-grep --pattern 'div[class*="tooltip"]'

Length of output: 75


Script:

#!/bin/bash
# Let's try a broader search for tooltip-related styles
rg -g '*.{css,scss,styled.ts,styles.ts}' -i 'tooltip'

# Check for styled-components usage in tooltip component
rg -t typescript -t typescriptreact "styled" packages/components/tooltip/

# Look for any CSS modules or style imports in tooltip
rg -t typescript -t typescriptreact "import.*style|import.*css" packages/components/tooltip/

Length of output: 292


Script:

#!/bin/bash
# Search for tooltip styles with correct ripgrep file extensions
rg -g '*.{css,scss,ts,tsx}' -i 'tooltip.*{style|css}'

# Check the tooltip component file itself for styling approach
cat packages/components/tooltip/src/tooltip.tsx

# Look for any style-related imports or styled-components usage
rg -g '*.{ts,tsx}' "import.*styled|import.*css|import.*style" packages/components/tooltip/

Length of output: 3340


Script:

#!/bin/bash
# Check the Component prop type and usage
cat packages/components/tooltip/src/use-tooltip.ts

# Look for any default styles or className props being passed
rg -g '*.{ts,tsx}' "getTooltipProps|getTriggerProps" packages/components/tooltip/

Length of output: 9261

packages/components/tooltip/src/use-tooltip.ts (2)

7-7: LGTM: Clean import addition

The ReactElement import is appropriately added to support the new LazyElement type.


299-310: 🛠️ Refactor suggestion

Add support for server components

To fully address the PR objective of handling both lazy and server components, consider adding server component detection.

Let's verify if server components have a similar identifier:

 export function isLazyElement(element: LazyElement): boolean {
   if (typeof element !== "object" || element === null) {
     return false;
   }
 
   // Check if it's a ReactElement and has the $$typeof property of React.lazy
   const reactElement = element as ReactNode & {
     $$typeof: symbol;
   };
 
-  return reactElement.$$typeof === Symbol.for("react.lazy");
+  return (
+    reactElement.$$typeof === Symbol.for("react.lazy") ||
+    reactElement.$$typeof === Symbol.for("react.server.reference")
+  );
 }

Comment on lines +299 to +310
export function isLazyElement(element: LazyElement): boolean {
if (typeof element !== "object" || element === null) {
return false;
}

// Check if it's a ReactElement and has the $$typeof property of React.lazy
const reactElement = element as ReactNode & {
$$typeof: symbol;
};

return reactElement.$$typeof === Symbol.for("react.lazy");
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add JSDoc documentation and improve type safety

The function implementation is correct but could benefit from better documentation and type safety.

  1. Add JSDoc documentation:
+/**
+ * Checks if the given element is a React lazy component.
+ * @param element - The element to check
+ * @returns true if the element is a React lazy component, false otherwise
+ */
export function isLazyElement(element: LazyElement): boolean {
  1. Make it a type guard for better type safety:
-export function isLazyElement(element: LazyElement): boolean {
+export function isLazyElement(element: LazyElement): element is ReactElement {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export function isLazyElement(element: LazyElement): boolean {
if (typeof element !== "object" || element === null) {
return false;
}
// Check if it's a ReactElement and has the $$typeof property of React.lazy
const reactElement = element as ReactNode & {
$$typeof: symbol;
};
return reactElement.$$typeof === Symbol.for("react.lazy");
}
/**
* Checks if the given element is a React lazy component.
* @param element - The element to check
* @returns true if the element is a React lazy component, false otherwise
*/
export function isLazyElement(element: LazyElement): element is ReactElement {
if (typeof element !== "object" || element === null) {
return false;
}
// Check if it's a ReactElement and has the $$typeof property of React.lazy
const reactElement = element as ReactNode & {
$$typeof: symbol;
};
return reactElement.$$typeof === Symbol.for("react.lazy");
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant