Skip to content
Advertisement

How to avoid the ‘no-param-reassign’ rule with a input’s handleChange?

I’m working to build a React Textarea that auto grows/shrinks as the user types. I’ve built my component inspired by this codepen: https://codepen.io/Libor_G/pen/eyzwOx

While I have this working nicely, I’m getting an es-lint error I’m unsure how to correctly resolve. eslint is not liking that I’m using the event param in the handleChange function.

What is the right way to resolve this?

My REACT UIC:

import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';

const TEXTAREA_LINE_HEIGHT = 24;
const PADDING = 16;

const StyledTextArea = styled.textarea`
  resize: none;
  width: 100%;
  padding: ${PADDING}px;

  line-height: ${TEXTAREA_LINE_HEIGHT}px;
  font-size: 17px;
`;


class TextArea extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: '',
      rows: 1,
      minRows: 1,
      maxRows: 3,
    };
  }

  handleChange = (event) => {
    const { minRows, maxRows } = this.state;


    const previousRows = event.target.rows;
    event.target.rows = minRows; // reset number of rows in textarea

    const currentRows = Math.floor((event.target.scrollHeight - (PADDING * 2)) / TEXTAREA_LINE_HEIGHT);

    if (currentRows === previousRows) {
      event.target.rows = currentRows;
    }

    if (currentRows >= maxRows) {
      event.target.rows = maxRows;
      event.target.scrollTop = event.target.scrollHeight;
    }

    this.setState({
      value: event.target.value,
      rows: currentRows < maxRows ? currentRows : maxRows,
    });
  };

  render = () => {
    const {
      name,
      placeholder,
    } = this.props;

    return (
      <StyledTextArea
        innerRef={(ref) => {
          this.textAreaRef = ref;
        }}
        name={name}
        placeholder={placeholder}
        rows={this.state.rows}
        value={this.state.value}
        onChange={this.handleChange}
      />
    );
  }
}

TextArea.defaultProps = {
  name: null,
  placeholder: null,
};

TextArea.propTypes = {
  name: PropTypes.string,
  placeholder: PropTypes.string,
};

export default TextArea;

Advertisement

Answer

You can either disable the rule as I mentioned in my comment like the following: /*eslint no-param-reassign: ["error", { "props": false }]*/

Or if you don’t prefer to ignore eslint, you can assign your param to a new variable:

const ev = event and you can use ev instead of event.

Advertisement