Skip to content

feat: allow HTML attributes passthrough on ResponsiveContainer#7168

Merged
PavelVanecek merged 1 commit into
recharts:mainfrom
techcodie:feat/responsive-container-html-attrs
May 28, 2026
Merged

feat: allow HTML attributes passthrough on ResponsiveContainer#7168
PavelVanecek merged 1 commit into
recharts:mainfrom
techcodie:feat/responsive-container-html-attrs

Conversation

@techcodie

@techcodie techcodie commented Mar 25, 2026

Copy link
Copy Markdown
Contributor

Summary

ResponsiveContainer previously did not accept standard HTML attributes like data-testid, aria-label, role, etc. Users who needed these for testing or accessibility had to wrap the container in an extra div.

Changes

  • Extended Props interface to include React.HTMLAttributes<HTMLDivElement> (with Omit for internally-managed props: id, className, style, onResize)
  • Spread remaining props (...others) onto the root container div
  • Simplified style prop type from Omit<CSSProperties, keyof Props> to CSSProperties — the previous type was overly restrictive and stripped valid CSS properties like color and width that happened to share names with component props

Usage

<ResponsiveContainer data-testid="my-chart" aria-label="Sales chart" role="img">
  <BarChart data={data}>...</BarChart>
</ResponsiveContainer>

Tests

Added test/component/ResponsiveContainerDataTest.spec.tsx verifying data-testid passthrough.
All 26 existing ResponsiveContainer tests continue to pass.

Summary by CodeRabbit

  • New Features

    • ResponsiveContainer now accepts and forwards additional standard HTML/div attributes (e.g., data-*, ARIA, event handlers) and uses a simplified style prop for easier styling.
  • Tests

    • Added a test to verify ResponsiveContainer forwards custom HTML attributes and renders as expected.

Review Change Stack

@coderabbitai

coderabbitai Bot commented Mar 25, 2026

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3a144c6a-60ff-4d1e-98e7-ef746de3b9c1

📥 Commits

Reviewing files that changed from the base of the PR and between fdd2a3a and f41b1ad.

📒 Files selected for processing (1)
  • src/component/ResponsiveContainer.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/component/ResponsiveContainer.tsx

Walkthrough

The ResponsiveContainer Props interface is enhanced to accept additional standard HTML div attributes through extending React.HTMLAttributes, excluding id, className, style, and onResize. The style prop type is simplified, and the component forwards remaining props to the rendered div element. A new test is added.

Changes

Cohort / File(s) Summary
Component Enhancement
src/component/ResponsiveContainer.tsx
Updated Props interface to extend React.HTMLAttributes with explicit omissions. Changed style prop type from Omit<CSSProperties, keyof Props> to plain CSSProperties. Component now forwards additional HTML attributes via ...others to the rendered div element.
Test Addition
test/component/ResponsiveContainerDataTest.spec.tsx
New test spec added to verify ResponsiveContainer accepts and properly forwards the data-testid prop alongside initialDimension, using React Testing Library to query and assert the element's presence in the DOM.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested reviewers

  • ckifer
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and accurately describes the main change: extending ResponsiveContainer to accept and forward HTML attributes via React.HTMLAttributes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/component/ResponsiveContainer.tsx (1)

257-304: ⚠️ Potential issue | 🟠 Major

HTML attributes are not forwarded in all code paths.

The ResponsiveContainer component has three return paths, but only one forwards HTML attributes:

  1. Line 264 (nested container): Returns only props.children — attributes lost
  2. Lines 294-298 (fixed dimensions): Returns only context provider — attributes lost
  3. Line 304 (size observer): Uses SizeDetectorContainer — attributes forwarded ✓

When users provide fixed numeric width and height (or when nested), props like data-testid, aria-label, and role will be silently dropped.

🐛 Proposed fix to forward attributes in all paths
   if (isPositiveNumber(responsiveContainerContext.width) && isPositiveNumber(responsiveContainerContext.height)) {
-    return props.children;
+    return <SizeDetectorContainer {...props} ref={ref} />;
   }

And for the fixed dimensions path, consider wrapping children in a div with the HTML attributes, or always use SizeDetectorContainer:

   if (isNumber(calculatedWidth) && isNumber(calculatedHeight)) {
-    return (
-      <ResponsiveContainerContextProvider width={calculatedWidth} height={calculatedHeight}>
-        {props.children}
-      </ResponsiveContainerContextProvider>
-    );
+    return <SizeDetectorContainer {...props} width={width} height={height} ref={ref} />;
   }

Alternatively, if avoiding the extra div is important for these cases, document this limitation clearly.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/component/ResponsiveContainer.tsx` around lines 257 - 304,
ResponsiveContainer currently returns three different roots but only the
SizeDetectorContainer path forwards HTML attributes, so attributes like
data-testid/aria-label are dropped when returning props.children (nested case)
or ResponsiveContainerContextProvider (fixed-dimensions case). Fix by ensuring
HTML attributes from props are passed through on all return paths: spread the
leftover DOM props (e.g., using restProps or extracting known non-DOM props)
onto a wrapper element or onto ResponsiveContainerContextProvider when returning
fixed dimensions, and when returning props.children in the nested-container case
wrap children in a fragment that preserves attributes (e.g., a <div> or the
existing SizeDetectorContainer) so attributes are applied; update
ResponsiveContainer to forward ref and DOM props consistently and reuse
SizeDetectorContainer or ResponsiveContainerContextProvider wrappers to
centralize attribute forwarding (references: ResponsiveContainer,
SizeDetectorContainer, ResponsiveContainerContextProvider,
useResponsiveContainerContext, getDefaultWidthAndHeight,
calculateChartDimensions).
🧹 Nitpick comments (1)
test/component/ResponsiveContainerDataTest.spec.tsx (1)

7-18: Consider adding tests for other HTML attributes and edge cases.

The test only verifies data-testid with initialDimension. Consider adding coverage for:

  1. Other HTML attributes mentioned in the PR (e.g., aria-label, role)
  2. The case where fixed numeric width and height are provided (which currently may not forward attributes — see the issue flagged in the source file)
💡 Additional test cases to consider
test('should pass down aria-label and role attributes', () => {
  const { getByTestId } = render(
    <ResponsiveContainer
      data-testid="accessible-chart"
      aria-label="Sales chart"
      role="img"
      initialDimension={{ width: 100, height: 100 }}
    >
      <BarChart width={100} height={100} data={[]}>
        <Bar dataKey="value" />
      </BarChart>
    </ResponsiveContainer>,
  );
  vi.runOnlyPendingTimers();

  const container = getByTestId('accessible-chart');
  expect(container).toHaveAttribute('aria-label', 'Sales chart');
  expect(container).toHaveAttribute('role', 'img');
});

test('should pass down data-testid with fixed dimensions', () => {
  const { getByTestId } = render(
    <ResponsiveContainer data-testid="fixed-chart" width={200} height={200}>
      <BarChart width={200} height={200} data={[]}>
        <Bar dataKey="value" />
      </BarChart>
    </ResponsiveContainer>,
  );
  vi.runOnlyPendingTimers();

  // This test may fail until the source issue is fixed
  expect(getByTestId('fixed-chart')).toBeInTheDocument();
});
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/component/ResponsiveContainerDataTest.spec.tsx` around lines 7 - 18, Add
tests to cover forwarding other HTML attributes and the fixed-dimension path:
render ResponsiveContainer (use the ResponsiveContainer component symbol) with
initialDimension and with aria-label and role props and assert via getByTestId
that the root element has aria-label and role; also add a separate test
rendering ResponsiveContainer with numeric width and height props (width,
height) and data-testid and assert that getByTestId('fixed-chart') is present
(run timers with vi.runOnlyPendingTimers where needed). These tests will target
attribute forwarding for both the initialDimension path and the fixed
width/height path so you can detect and fix the reported attribute-forwarding
bug.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@test/component/ResponsiveContainerDataTest.spec.tsx`:
- Around line 6-18: Add fake timer setup and advancement around the render in
this test: call vi.useFakeTimers() before calling render(…) and after the render
call invoke vi.runOnlyPendingTimers() to flush timers; then replace the
container.querySelector assertion with the render result's
getByTestId('my-container') (from the render return) to assert existence. Update
the test for ResponsiveContainer and its render usage accordingly and ensure
timers are restored/left as per suite conventions if needed.

---

Outside diff comments:
In `@src/component/ResponsiveContainer.tsx`:
- Around line 257-304: ResponsiveContainer currently returns three different
roots but only the SizeDetectorContainer path forwards HTML attributes, so
attributes like data-testid/aria-label are dropped when returning props.children
(nested case) or ResponsiveContainerContextProvider (fixed-dimensions case). Fix
by ensuring HTML attributes from props are passed through on all return paths:
spread the leftover DOM props (e.g., using restProps or extracting known non-DOM
props) onto a wrapper element or onto ResponsiveContainerContextProvider when
returning fixed dimensions, and when returning props.children in the
nested-container case wrap children in a fragment that preserves attributes
(e.g., a <div> or the existing SizeDetectorContainer) so attributes are applied;
update ResponsiveContainer to forward ref and DOM props consistently and reuse
SizeDetectorContainer or ResponsiveContainerContextProvider wrappers to
centralize attribute forwarding (references: ResponsiveContainer,
SizeDetectorContainer, ResponsiveContainerContextProvider,
useResponsiveContainerContext, getDefaultWidthAndHeight,
calculateChartDimensions).

---

Nitpick comments:
In `@test/component/ResponsiveContainerDataTest.spec.tsx`:
- Around line 7-18: Add tests to cover forwarding other HTML attributes and the
fixed-dimension path: render ResponsiveContainer (use the ResponsiveContainer
component symbol) with initialDimension and with aria-label and role props and
assert via getByTestId that the root element has aria-label and role; also add a
separate test rendering ResponsiveContainer with numeric width and height props
(width, height) and data-testid and assert that getByTestId('fixed-chart') is
present (run timers with vi.runOnlyPendingTimers where needed). These tests will
target attribute forwarding for both the initialDimension path and the fixed
width/height path so you can detect and fix the reported attribute-forwarding
bug.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a8c096c2-7bab-48eb-98b9-b75c21e3508b

📥 Commits

Reviewing files that changed from the base of the PR and between 5b10788 and fdd2a3a.

📒 Files selected for processing (2)
  • src/component/ResponsiveContainer.tsx
  • test/component/ResponsiveContainerDataTest.spec.tsx

Comment thread test/component/ResponsiveContainerDataTest.spec.tsx
ResponsiveContainer now extends React.HTMLAttributes<HTMLDivElement>,
allowing users to pass standard HTML attributes like data-testid,
aria-label, role, etc. to the underlying container div.

This enables better testing (data-testid) and accessibility (aria-*)
without requiring wrapper elements.

Conflicting internal props (id, className, style, onResize) are
omitted from the HTML attributes to avoid type collisions.
@PavelVanecek
PavelVanecek force-pushed the feat/responsive-container-html-attrs branch from fdd2a3a to f41b1ad Compare May 28, 2026 06:28
@codecov

codecov Bot commented May 28, 2026

Copy link
Copy Markdown

Bundle Report

Changes will increase total bundle size by 2.07kB (0.04%) ⬆️. This is within the configured threshold ✅

Detailed changes
Bundle name Size Change
recharts/bundle-cjs 1.4MB 771 bytes (0.06%) ⬆️
recharts/bundle-es6 1.23MB 771 bytes (0.06%) ⬆️
recharts/bundle-umd 584.84kB 527 bytes (0.09%) ⬆️

Affected Assets, Files, and Routes:

view changes for bundle: recharts/bundle-cjs

Assets Changed:

Asset Name Size Change Total Size Change (%)
component/ResponsiveContainer.js 771 bytes 14.19kB 5.75% ⚠️
view changes for bundle: recharts/bundle-es6

Assets Changed:

Asset Name Size Change Total Size Change (%)
component/ResponsiveContainer.js 771 bytes 12.79kB 6.41% ⚠️
view changes for bundle: recharts/bundle-umd

Assets Changed:

Asset Name Size Change Total Size Change (%)
Recharts.js 527 bytes 584.84kB 0.09%

@codecov

codecov Bot commented May 28, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.05%. Comparing base (007a85c) to head (f41b1ad).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #7168   +/-   ##
=======================================
  Coverage   89.05%   89.05%           
=======================================
  Files         548      548           
  Lines       40575    40577    +2     
  Branches     5581     5580    -1     
=======================================
+ Hits        36134    36136    +2     
  Misses       4432     4432           
  Partials        9        9           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@PavelVanecek
PavelVanecek merged commit cd8b07a into recharts:main May 28, 2026
55 checks passed
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.

2 participants