typescript.react.best-practice.react-legacy-component.react-legacy-component

profile photo of semgrepsemgrep
Author
4,056
Download Count*

Legacy component lifecycle was detected - $METHOD.

Run Locally

Run in CI

Defintion

rules:
  - id: react-legacy-component
    patterns:
      - pattern: |
          $METHOD(...) {
            ...
          }
      - metavariable-regex:
          metavariable: $METHOD
          regex: componentWillMount|componentWillReceiveProps|componentWillUpdate
    message: Legacy component lifecycle was detected - $METHOD.
    languages:
      - typescript
      - javascript
    severity: WARNING
    metadata:
      category: best-practice
      technology:
        - react
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]

Examples

react-legacy-component.jsx

class Test1 extends React.Component {
  state = {
    value: ''
  };
// ruleid: react-legacy-component
  componentWillReceiveProps(nextProps) {
    this.setState({ value: nextProps.value });
  }
  handleChange = (e) => {
    this.setState({ value: e.target.value });
  };
  render() {
    return (
      <input
        value={this.state.value}
        onChange={this.handleChange}
      />
    );
  }
}

class OkComponent1 extends Component {
// ok: react-legacy-component
  componentDidMount() {
    this.node.scrollIntoView();
  }

  render() {
    return <div ref={node => this.node = node} />
  }
}

react-legacy-component.tsx

class Test1 extends React.Component {
  state = {
    value: ''
  };
// ruleid: react-legacy-component
  componentWillReceiveProps(nextProps) {
    this.setState({ value: nextProps.value });
  }
  handleChange = (e) => {
    this.setState({ value: e.target.value });
  };
  render() {
    return (
      <input
        value={this.state.value}
        onChange={this.handleChange}
      />
    );
  }
}

class OkComponent1 extends Component {
// ok: react-legacy-component
  componentDidMount() {
    this.node.scrollIntoView();
  }

  render() {
    return <div ref={node => this.node = node} />
  }
}