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

[Fix] button-has-type: improve message when non-static value is used #2625

Merged
merged 2 commits into from Apr 17, 2020
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/rules/button-has-type.md
Expand Up @@ -10,6 +10,7 @@ The following patterns are considered errors:
```jsx
var Hello = <button>Hello</button>
var Hello = <button type="foo">Hello</button>
var Hello = <button type={foo}>Hello</button>

var Hello = React.createElement('button', {}, 'Hello')
var Hello = React.createElement('button', {type: 'foo'}, 'Hello')
Expand Down
18 changes: 11 additions & 7 deletions lib/rules/button-has-type.js
Expand Up @@ -72,8 +72,8 @@ module.exports = {
});
}

function checkValue(node, value, quoteFn) {
const q = quoteFn || (x => `"${x}"`);
function checkValue(node, value) {
const q = x => `"${x}"`;
if (!(value in configuration)) {
context.report({
node,
Expand All @@ -100,12 +100,16 @@ module.exports = {
return;
}

const propValue = getLiteralPropValue(typeProp);
if (!propValue && typeProp.value && typeProp.value.expression) {
checkValue(node, typeProp.value.expression.name, x => `\`${x}\``);
} else {
checkValue(node, propValue);
if (typeProp.value.type === 'JSXExpressionContainer') {
context.report({
node: typeProp,
message: 'The button type attribute must be specified by a static string'
});
return;
}

const propValue = getLiteralPropValue(typeProp);
checkValue(node, propValue);
},
CallExpression(node) {
if (!isCreateElement(node, context)) {
Expand Down
14 changes: 13 additions & 1 deletion tests/lib/rules/button-has-type.js
Expand Up @@ -73,7 +73,13 @@ ruleTester.run('button-has-type', rule, {
{
code: '<button type={foo}/>',
errors: [{
message: '`foo` is an invalid value for button type attribute'
message: 'The button type attribute must be specified by a static string'
}]
},
{
code: '<button type={"foo"}/>',
errors: [{
message: 'The button type attribute must be specified by a static string'
}]
},
{
Expand Down Expand Up @@ -112,6 +118,12 @@ ruleTester.run('button-has-type', rule, {
pragma: 'Foo'
}
}
},
{
code: 'function Button({ type, ...extraProps }) { const button = type; return <button type={button} {...extraProps} />; }',
errors: [{
message: 'The button type attribute must be specified by a static string'
}]
}
]
});