Skip to content
Permalink
Browse files

Fix: Map className and htmlFor attributes correctly

  • Loading branch information...
antross authored and molant committed Oct 25, 2019
1 parent f850f22 commit a03165a02426780ec3f42d60b93887266b78a338
Showing with 25 additions and 2 deletions.
  1. +17 −2 packages/parser-jsx/src/parser.ts
  2. +8 −0 packages/parser-jsx/tests/tests.ts
@@ -15,7 +15,7 @@ import { JSXAttribute, JSXElement, JSXExpressionContainer, JSXText, Node, Script
type ChildMap = Map<JSXElement, Array<ElementData | TextData>>;
type RootMap = Map<Node, ElementData>;

const debug: debug.IDebugger = d(__filename);
const debug = d(__filename);

/**
* Check if the provided `Node` is a native HTML element in JSX.
@@ -61,6 +61,21 @@ const mapLocation = (node: Node, { startColumnOffset = 0 } = {}): parse5.Locatio
};
};

/**
* Convert a JSX attribute name to its HTML equivalent.
*/
const mapAttributeName = (name: string) => {
if (name === 'className') {
return 'class';
}

if (name === 'htmlFor') {
return 'for';
}

return name;
};

/**
* Translate collections of `JSXAttribute`s to their HTML AST equivalent.
*/
@@ -81,7 +96,7 @@ const mapAttributes = (node: JSXElement) => {
continue;
}

const { name } = attribute.name;
const name = mapAttributeName(attribute.name.name);

if (!attribute.value) {
attribs[name] = '';
@@ -155,3 +155,11 @@ test('It translates source locations correctly', async (t) => {
t.is(column, 13);
t.is(line, 1);
});

test('It translates JSX attributes to HTML attributes', async (t) => {
const { document } = await parseJSX(`const jsx = <label className="foo" htmlFor="bar">Label</label>;`);
const label = document.querySelectorAll('label')[0];

t.is(label.getAttribute('class'), 'foo');
t.is(label.getAttribute('for'), 'bar');
});

0 comments on commit a03165a

Please sign in to comment.
You can’t perform that action at this time.