Skip to content

Commit a8672db

Browse files
authoredApr 8, 2022
Fix #214 to prevent duplicate selected attribute from being added to <option> elements if it already exists (#215)
1 parent 936f71d commit a8672db

File tree

3 files changed

+27
-3
lines changed

3 files changed

+27
-3
lines changed
 

‎.changeset/twenty-weeks-fetch.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'preact-render-to-string': patch
3+
---
4+
5+
Don't add selected attribute to <option> elements if they already contain that attribute

‎src/index.js

+8-3
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,7 @@ const SHALLOW = { shallow: true };
1515
// components without names, kept as a hash for later comparison to return consistent UnnamedComponentXX names.
1616
const UNNAMED = [];
1717

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

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

@@ -296,7 +295,13 @@ function _renderToString(vnode, context, opts, inner, isSvgMode, selectValue) {
296295
if (nodeName === 'select') {
297296
selectValue = v;
298297
continue;
299-
} else if (nodeName === 'option' && selectValue == v) {
298+
} else if (
299+
// If we're looking at an <option> and it's the currently selected one
300+
nodeName === 'option' &&
301+
selectValue == v &&
302+
// and the <option> doesn't already have a selected attribute on it
303+
typeof props.selected === 'undefined'
304+
) {
300305
s += ` selected`;
301306
}
302307
}

‎test/render.test.js

+14
Original file line numberDiff line numberDiff line change
@@ -1139,6 +1139,20 @@ describe('render', () => {
11391139
);
11401140
});
11411141

1142+
it('should not add a selected attribute if one already exists', () => {
1143+
let res = render(
1144+
<select value="B">
1145+
<option value="A">A</option>
1146+
<option selected value="B">
1147+
B
1148+
</option>
1149+
</select>
1150+
);
1151+
expect(res).to.equal(
1152+
'<select><option value="A">A</option><option selected value="B">B</option></select>'
1153+
);
1154+
});
1155+
11421156
it('should render select value on option with a Fragment', () => {
11431157
let res = render(
11441158
<select value="B">

0 commit comments

Comments
 (0)
Please sign in to comment.