Skip to content

Commit

Permalink
Fix #214 to prevent duplicate selected attribute from being added to …
Browse files Browse the repository at this point in the history
…<option> elements if it already exists (#215)
  • Loading branch information
AleksandrHovhannisyan authored Apr 8, 2022
1 parent 936f71d commit a8672db
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/twenty-weeks-fetch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'preact-render-to-string': patch
---

Don't add selected attribute to <option> elements if they already contain that attribute
11 changes: 8 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ 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 @@ -296,7 +295,13 @@ function _renderToString(vnode, context, opts, inner, isSvgMode, selectValue) {
if (nodeName === 'select') {
selectValue = v;
continue;
} else if (nodeName === 'option' && selectValue == v) {
} else if (
// If we're looking at an <option> and it's the currently selected one
nodeName === 'option' &&
selectValue == v &&
// and the <option> doesn't already have a selected attribute on it
typeof props.selected === 'undefined'
) {
s += ` selected`;
}
}
Expand Down
14 changes: 14 additions & 0 deletions test/render.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1139,6 +1139,20 @@ describe('render', () => {
);
});

it('should not add a selected attribute if one already exists', () => {
let res = render(
<select value="B">
<option value="A">A</option>
<option selected value="B">
B
</option>
</select>
);
expect(res).to.equal(
'<select><option value="A">A</option><option selected value="B">B</option></select>'
);
});

it('should render select value on option with a Fragment', () => {
let res = render(
<select value="B">
Expand Down

0 comments on commit a8672db

Please sign in to comment.