Skip to content

Commit

Permalink
fix(lint/useJsxKeyInIterable): handle ternaries properly (#2701)
Browse files Browse the repository at this point in the history
  • Loading branch information
dyc3 authored May 5, 2024
1 parent ba4f93b commit 84b256f
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,19 @@ fn handle_potential_react_component(
let node = unwrap_parenthesis(node)?;

if is_inside_jsx {
if let AnyJsExpression::JsConditionalExpression(node) = node {
let consequent =
handle_potential_react_component(node.consequent().ok()?, model, is_inside_jsx);
let alternate =
handle_potential_react_component(node.alternate().ok()?, model, is_inside_jsx);

return match (consequent, alternate) {
(Some(consequent), Some(alternate)) => Some([consequent, alternate].concat()),
(Some(consequent), None) => Some(consequent),
(None, Some(alternate)) => Some(alternate),
(None, None) => None,
};
}
if let Some(node) = ReactComponentExpression::cast_ref(node.syntax()) {
let range = handle_react_component(node, model)?;
Some(vec![range])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -520,6 +520,25 @@ invalid.jsx:33:8 lint/correctness/useJsxKeyInIterable ━━━━━━━━
i Check the React documentation.
```

```
invalid.jsx:33:29 lint/correctness/useJsxKeyInIterable ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
! Missing key property for this element in iterable.
31 │ (<h1>{[<h1></h1>, <h1></h1>, <h1></h1>]}</h1>)
32 │
> 33 │ (<h1>{[<h1></h1>, xyz, abc? <h2></h2>: bcd]}</h1>)
│ ^^^^
34 │
35 │ (<h1>{data.map(c => <h1></h1>)}</h1>)
i The order of the items may change, and having a key can help React identify which item was moved.
i Check the React documentation.
```

```
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,5 @@ React.Children.map(c => React.cloneElement(c, {key: c}));
<>{data.reduce((a, b) => Math.max(a, b), 0)}</>

<>{data.reduce((a, b) => a > b ? a : b, 0)}</>

<>{data.map(a => a > 4 ? <h1 key={a}>{a}</h1> : <h2 key={a}>{a}</h2>)}</>
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,6 @@ React.Children.map(c => React.cloneElement(c, {key: c}));

<>{data.reduce((a, b) => a > b ? a : b, 0)}</>

<>{data.map(a => a > 4 ? <h1 key={a}>{a}</h1> : <h2 key={a}>{a}</h2>)}</>

```

0 comments on commit 84b256f

Please sign in to comment.