Skip to main content

react_auditor/rules/react/
no_array_index_key.rs

1use oxc_ast::ast::Program;
2use oxc_ast_visit::Visit;
3use oxc_semantic::Semantic;
4
5use crate::rules::{Rule, RuleFinding, RuleMeta, Severity};
6
7pub struct NoArrayIndexKey;
8
9const RULE_META: RuleMeta = RuleMeta {
10    id: "no-array-index-key",
11    default_severity: Severity::Warning,
12    category: "react",
13    description: "Avoid using array index as key",
14};
15
16fn is_index_name(name: &str) -> bool {
17    matches!(name, "index" | "i" | "j" | "idx" | "ind" | "key")
18}
19
20impl Rule for NoArrayIndexKey {
21    fn meta(&self) -> &RuleMeta {
22        &RULE_META
23    }
24
25    fn run(&self, program: &Program, _semantic: &Semantic, source_text: &str) -> Vec<RuleFinding> {
26        let mut collector = ArrayIndexKeyCollector {
27            findings: Vec::new(),
28            source: source_text,
29        };
30        collector.visit_program(program);
31        collector.findings
32    }
33}
34
35struct ArrayIndexKeyCollector<'a> {
36    findings: Vec<RuleFinding>,
37    source: &'a str,
38}
39
40impl<'a> Visit<'a> for ArrayIndexKeyCollector<'a> {
41    fn visit_jsx_opening_element(&mut self, el: &oxc_ast::ast::JSXOpeningElement<'a>) {
42        for attr_item in &el.attributes {
43            if let oxc_ast::ast::JSXAttributeItem::Attribute(attr) = attr_item {
44                let is_key = matches!(&attr.name, oxc_ast::ast::JSXAttributeName::Identifier(id) if id.name.as_str() == "key");
45                if !is_key {
46                    continue;
47                }
48                if let Some(val) = &attr.value
49                    && let oxc_ast::ast::JSXAttributeValue::ExpressionContainer(container) = val
50                    && matches!(&container.expression, oxc_ast::ast::JSXExpression::Identifier(ident) if is_index_name(ident.name.as_str()))
51                {
52                    let start = attr.span.start as usize;
53                    let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
54                    let line = self.source[..start].lines().count().max(1);
55                    self.findings.push(RuleFinding {
56                        line,
57                        column: col + 1,
58                        message: "Avoid using array index as `key` — prefer a stable unique ID"
59                            .to_string(),
60                    });
61                }
62            }
63        }
64    }
65}