Skip to main content

react_auditor/rules/react/
no_missing_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 NoMissingKey;
8
9const RULE_META: RuleMeta = RuleMeta {
10    id: "no-missing-key",
11    default_severity: Severity::Error,
12    category: "react",
13    description: "List items should have a `key` prop",
14};
15
16impl Rule for NoMissingKey {
17    fn meta(&self) -> &RuleMeta {
18        &RULE_META
19    }
20
21    fn run(&self, program: &Program, _semantic: &Semantic, source_text: &str) -> Vec<RuleFinding> {
22        let mut collector = MissingKeyCollector {
23            findings: Vec::new(),
24            source: source_text,
25        };
26        collector.visit_program(program);
27        collector.findings
28    }
29}
30
31struct MissingKeyCollector<'a> {
32    findings: Vec<RuleFinding>,
33    source: &'a str,
34}
35
36impl<'a> Visit<'a> for MissingKeyCollector<'a> {
37    fn visit_jsx_opening_element(&mut self, el: &oxc_ast::ast::JSXOpeningElement<'a>) {
38        let has_key = el.attributes.iter().any(|attr| {
39            if let oxc_ast::ast::JSXAttributeItem::Attribute(a) = attr {
40                matches!(&a.name, oxc_ast::ast::JSXAttributeName::Identifier(id) if id.name.as_str() == "key")
41            } else {
42                false
43            }
44        });
45
46        if !has_key {
47            let start = el.span.start as usize;
48            let line = self.source[..start].lines().count().max(1);
49            let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
50
51            let name_str = match &el.name {
52                oxc_ast::ast::JSXElementName::Identifier(id) => Some(id.name.as_str()),
53                oxc_ast::ast::JSXElementName::IdentifierReference(id) => Some(id.name.as_str()),
54                _ => None,
55            };
56
57            if let Some(name) = name_str
58                && name.chars().next().is_some_and(|c| c.is_uppercase())
59            {
60                self.findings.push(RuleFinding {
61                    line,
62                    column: col + 1,
63                    message: format!("Component `<{name}>` is missing a `key` prop"),
64                });
65            }
66        }
67    }
68}