Skip to content

Commit

Permalink
fix: Serialize defaultChecked & defaultSelected (#224)
Browse files Browse the repository at this point in the history
* fix: Serialize defaultChecked as checked attr

* docs: Adding changeset

* fix: Serialize defaultSelected as selected attr
  • Loading branch information
rschristian committed Jul 8, 2022
1 parent 31ac323 commit 645f3cb
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/cyan-students-unite.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'preact-render-to-string': patch
---

Ensures `defaultChecked` is serialized as `checked` attribute
9 changes: 7 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ const SHALLOW = { shallow: true };
// components without names, kept as a hash for later comparison to return consistent UnnamedComponentXX names.
const UNNAMED = [];

const VOID_ELEMENTS = /^(area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)$/;
const VOID_ELEMENTS =
/^(area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)$/;

const UNSAFE_NAME = /[\s\n\\/='"\0<>]/;

Expand Down Expand Up @@ -258,10 +259,14 @@ function _renderToString(vnode, context, opts, inner, isSvgMode, selectValue) {

if (name === 'defaultValue') {
name = 'value';
} else if (name === 'defaultChecked') {
name = 'checked';
} else if (name === 'defaultSelected') {
name = 'selected';
} else if (name === 'className') {
if (typeof props.class !== 'undefined') continue;
name = 'class';
} else if (isSvgMode && name.match(/^xlink:?./)) {
} else if (isSvgMode && /^xlink:?./.test(name)) {
name = name.toLowerCase().replace(/^xlink:?/, 'xlink:');
}

Expand Down
14 changes: 14 additions & 0 deletions test/render.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,20 @@ describe('render', () => {
expect(rendered).to.equal(expected);
});

it('should serialize defaultChecked prop to the checked attribute', () => {
let rendered = render(<input type="checkbox" defaultChecked />),
expected = `<input type="checkbox" checked />`;

expect(rendered).to.equal(expected);
});

it('should serialize defaultSelected prop to the selected attribute', () => {
let rendered = render(<option defaultSelected />),
expected = `<option selected></option>`;

expect(rendered).to.equal(expected);
});

it('should include boolean aria-* attributes', () => {
let rendered = render(<div aria-hidden aria-whatever={false} />),
expected = `<div aria-hidden="true" aria-whatever="false"></div>`;
Expand Down

0 comments on commit 645f3cb

Please sign in to comment.