Skip to content

Commit fbfbc8c

Browse files
Merge pull request #2452 from Lay-quq/contrib/html-react-parser-style-case
2 parents 04dfdac + 6d72dba commit fbfbc8c

3 files changed

Lines changed: 25 additions & 4 deletions

File tree

‎__tests__/attributes-to-props/index.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,15 @@ describe('attributesToProps with SVG attribute', () => {
280280
describe('attributesToProps with style attribute', () => {
281281
const propsEmptyStyle = { style: {} };
282282

283+
it.each(['style', 'STYLE', 'StYlE'])(
284+
'converts %s to a style object',
285+
(attributeName) => {
286+
expect(
287+
attributesToProps({ [attributeName]: 'color: red; font-size: 12px' }),
288+
).toEqual({ style: { color: 'red', fontSize: '12px' } });
289+
},
290+
);
291+
283292
it.each([undefined, null] as unknown as string[])(
284293
'does not parse invalid value: %s',
285294
(style) => {

‎__tests__/index.test.tsx‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,17 @@ describe('htmlparser2 option', () => {
236236
});
237237
});
238238

239-
describe('invalid styles', () => {
239+
describe('styles', () => {
240+
it.each(['style', 'STYLE', 'StYlE'])(
241+
'renders an element with a %s attribute',
242+
(attributeName) => {
243+
const html = `<p ${attributeName}="color: red; font-size: 12px">Hello</p>`;
244+
expect(render(parse(html) as React.JSX.Element)).toBe(
245+
'<p style="color:red;font-size:12px">Hello</p>',
246+
);
247+
},
248+
);
249+
240250
it('copes with invalid styles', () => {
241251
const html = '<p style="font - size: 1em">X</p>';
242252
const reactElement = parse(html) as React.JSX.Element;

‎src/attributes-to-props.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,11 @@ export default function attributesToProps(
8484

8585
props[propName] = attributeValue;
8686

87+
// transform inline style to object after normalizing the attribute name
88+
if (propName === 'style') {
89+
setStyleProp(attributeValue, props);
90+
}
91+
8792
switch (propertyInfo?.type) {
8893
case BOOLEAN:
8994
props[propName] = true;
@@ -103,9 +108,6 @@ export default function attributesToProps(
103108
}
104109
}
105110

106-
// transform inline style to object
107-
setStyleProp(attributes.style, props);
108-
109111
return props;
110112
}
111113

0 commit comments

Comments
 (0)