typescript.react.best-practice.react-props-spreading.react-props-spreading

profile photo of semgrepsemgrep
Author
4,402
Download Count*

It's best practice to explicitly pass props to an HTML component rather than use the spread operator. The spread operator risks passing invalid HTML props to an HTML element, which can cause console warnings or worse, give malicious actors a way to inject unexpected attributes.

Run Locally

Run in CI

Defintion

rules:
  - id: react-props-spreading
    patterns:
      - pattern: <$X {...$PROPS} />
      - focus-metavariable: $PROPS
    message: It's best practice to explicitly pass props to an HTML component rather
      than use the spread operator. The spread operator risks passing invalid
      HTML props to an HTML element, which can cause console warnings or worse,
      give malicious actors a way to inject unexpected attributes.
    languages:
      - typescript
      - javascript
    severity: WARNING
    metadata:
      source-rule-url: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-props-no-spreading.md
      references:
        - https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-props-no-spreading.md
      category: best-practice
      technology:
        - react
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]

Examples

react-props-spreading.jsx

function Test1(props) {
// ruleid: react-props-spreading
    const el = <App {...props} />;
    return el;
}

function Test2(props) {
// ruleid: react-props-spreading
    const el = <MyCustomComponent {...props} some_other_prop={some_other_prop} />;
    return el;
}

function Test2(props, otherProps) {
    const {src, alt} = props;
    const {one_prop, two_prop} = otherProps;
// ok: react-props-spreading
    return <MyCustomComponent one_prop={one_prop} two_prop={two_prop} />;
}

react-props-spreading.tsx

function Test1(props) {
// ruleid: react-props-spreading
    const el = <App {...props} />;
    return el;
}

function Test2(props) {
// ruleid: react-props-spreading
    const el = <MyCustomComponent {...props} some_other_prop={some_other_prop} />;
    return el;
}

function Test2(props, otherProps) {
    const {src, alt} = props;
    const {one_prop, two_prop} = otherProps;
// ok: react-props-spreading
    return <MyCustomComponent one_prop={one_prop} two_prop={two_prop} />;
}