Skip to main content

react_auditor/rules/react/
no_missing_key.rs

1use oxc_ast::ast::Program;
2use oxc_ast_visit::Visit;
3use oxc_ast_visit::walk;
4use oxc_semantic::Semantic;
5
6use crate::rules::{Rule, RuleFinding, RuleMeta, Severity};
7
8pub struct NoMissingKey;
9
10const RULE_META: RuleMeta = RuleMeta {
11    id: "no-missing-key",
12    default_severity: Severity::Error,
13    category: "react",
14    description: "List items should have a `key` prop",
15};
16
17impl Rule for NoMissingKey {
18    fn meta(&self) -> &RuleMeta {
19        &RULE_META
20    }
21
22    fn run(&self, program: &Program, _semantic: &Semantic, source_text: &str) -> Vec<RuleFinding> {
23        let mut collector = MissingKeyCollector {
24            findings: Vec::new(),
25            source: source_text,
26            list_context_depth: 0,
27        };
28        collector.visit_program(program);
29        collector.findings
30    }
31}
32
33struct MissingKeyCollector<'a> {
34    findings: Vec<RuleFinding>,
35    source: &'a str,
36    list_context_depth: usize,
37}
38
39impl<'a> Visit<'a> for MissingKeyCollector<'a> {
40    fn visit_call_expression(&mut self, expr: &oxc_ast::ast::CallExpression<'a>) {
41        let is_list_map = match &expr.callee {
42            oxc_ast::ast::Expression::StaticMemberExpression(member) => {
43                let prop = member.property.name.as_str();
44                prop == "map" || prop == "flatMap"
45            }
46            _ => false,
47        };
48
49        let has_callback = expr.arguments.first().is_some_and(|arg| {
50            matches!(
51                arg,
52                oxc_ast::ast::Argument::ArrowFunctionExpression(_)
53                    | oxc_ast::ast::Argument::FunctionExpression(_)
54            )
55        });
56
57        if is_list_map && has_callback {
58            self.list_context_depth += 1;
59            walk::walk_call_expression(self, expr);
60            self.list_context_depth -= 1;
61        } else {
62            walk::walk_call_expression(self, expr);
63        }
64    }
65
66    fn visit_jsx_opening_element(&mut self, el: &oxc_ast::ast::JSXOpeningElement<'a>) {
67        if self.list_context_depth == 0 {
68            return;
69        }
70
71        let has_key = el.attributes.iter().any(|attr| {
72            if let oxc_ast::ast::JSXAttributeItem::Attribute(a) = attr {
73                matches!(&a.name, oxc_ast::ast::JSXAttributeName::Identifier(id) if id.name.as_str() == "key")
74            } else {
75                false
76            }
77        });
78
79        if !has_key {
80            let start = el.span.start as usize;
81            let line = self.source[..start].lines().count().max(1);
82            let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
83
84            let name_str = match &el.name {
85                oxc_ast::ast::JSXElementName::Identifier(id) => Some(id.name.as_str()),
86                oxc_ast::ast::JSXElementName::IdentifierReference(id) => Some(id.name.as_str()),
87                _ => None,
88            };
89
90            if let Some(name) = name_str
91                && name.chars().next().is_some_and(|c| c.is_uppercase())
92            {
93                self.findings.push(RuleFinding {
94                    line,
95                    column: col + 1,
96                    message: format!("Component `<{name}>` is missing a `key` prop"),
97                });
98            }
99        }
100    }
101}