Skip to content

fixjsx-curly-brace-presence: bail out checks when JSXElements are passed as props #2426

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

Merged
Merged
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
29 changes: 19 additions & 10 deletions lib/rules/jsx-curly-brace-presence.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,26 +114,21 @@ module.exports = {
* @param {ASTNode} JSXExpressionNode - The AST node with an unnecessary JSX expression
*/
function reportUnnecessaryCurly(JSXExpressionNode) {
const expression = JSXExpressionNode.expression;
const expressionType = expression.type;
const parentType = JSXExpressionNode.parent.type;
const isJSX = jsxUtil.isJSX(expression);

if (parentType === 'JSXAttribute' && isJSX) {
return;
}

context.report({
node: JSXExpressionNode,
message: 'Curly braces are unnecessary here.',
fix(fixer) {
const expression = JSXExpressionNode.expression;
const expressionType = expression.type;
const parentType = JSXExpressionNode.parent.type;

let textToReplace;
if (parentType === 'JSXAttribute') {
textToReplace = `"${expressionType === 'TemplateLiteral' ?
expression.quasis[0].value.raw :
expression.raw.substring(1, expression.raw.length - 1)
}"`;
} else if (isJSX) {
} else if (jsxUtil.isJSX(expression)) {
const sourceCode = context.getSourceCode();

textToReplace = sourceCode.getText(expression);
Expand Down Expand Up @@ -244,6 +239,20 @@ module.exports = {
}

function shouldCheckForUnnecessaryCurly(parent, node, config) {
// Bail out if the parent is a JSXAttribute & its contents aren't
// StringLiteral or TemplateLiteral since e.g
// <App prop1={<CustomEl />} prop2={<CustomEl>...</CustomEl>} />

if (
parent.type && parent.type === 'JSXAttribute' &&
(node.expression && node.expression.type &&
node.expression.type !== 'Literal' &&
node.expression.type !== 'StringLiteral' &&
node.expression.type !== 'TemplateLiteral')
) {
return false;
}

// If there are adjacent `JsxExpressionContainer` then there is no need,
// to check for unnecessary curly braces.
if (jsxUtil.isJSX(parent) && hasAdjacentJsxExpressionContainers(node, parent.children)) {
Expand Down