Skip to content

Commit 127e7a2

Browse files
committed
feature: @putout/operator-jsx: setAttributeValue
1 parent bd10588 commit 127e7a2

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

packages/operator-jsx/README.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,21 @@ Works this way:
7676
+<section className="world"/>
7777
```
7878

79+
### setAttributeValue(path: Path | Node, name: string, value: string)
80+
81+
Set `attribute` value:
82+
83+
```js
84+
setAttributeValue(node, 'className', 'hello');
85+
```
86+
87+
Works this way:
88+
89+
```diff
90+
-<section className="world"/>
91+
+<section className="hello"/>
92+
```
93+
7994
## License
8095

8196
MIT

packages/operator-jsx/lib/jsx.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,3 +71,10 @@ module.exports.removeAttributeValue = (path, name, attributeValue) => {
7171
if (value.includes(attributeValue))
7272
setLiteralValue(classAttribute.value, value.replace(RegExp(`\\s?${attributeValue}`), ''));
7373
};
74+
75+
module.exports.setAttributeValue = (node, name, value) => {
76+
const attributeNode = getAttributeNode(node, name);
77+
78+
if (attributeNode)
79+
setLiteralValue(attributeNode.value, value);
80+
};

packages/operator-jsx/lib/jsx.spec.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ const {
1616
getAttributeNode,
1717
getAttributeValue,
1818
addAttributeValue,
19+
setAttributeValue,
1920
removeAttributeValue,
2021
} = require('./jsx.js');
2122

@@ -169,6 +170,17 @@ test('putout: operator: jsx: removeAttributeValue', (t) => {
169170
t.end();
170171
});
171172

173+
test('putout: operator: jsx: setAttributeValue', (t) => {
174+
const node = template.ast.fresh('<hello className="hello"/>');
175+
setAttributeValue(node, 'className', 'world');
176+
177+
const result = print(node);
178+
const expected = `<hello className="world"/>;\n`;
179+
180+
t.equal(result, expected);
181+
t.end();
182+
});
183+
172184
test('putout: operator: jsx: removeAttributeValue: no path', (t) => {
173185
const [error] = tryCatch(removeAttributeValue, null, 'className', 'world');
174186

0 commit comments

Comments
 (0)