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

Don't add selected attribute to <option> if it already exists #215

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)$/;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

(Prettier formatted this)


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