Custom Grommet TextArea not changing rows prop on initial input

17 views Asked by At

I have created the a custom Grommet TextArea component, with the idea of it having the ability to change its rows prop based on the input. In the current usage it is also autopopulated on form load.

The first time around it was working inside the parent form with the expected behavior, however once it was exported it would not change the rows property in on the initial input population, only if the input is changed afterwards.

I can see that the rows property is calculated correctly on the initial load as well, however it would not change the height of the TextArea.

The exported custom component:

import React, { useState } from 'react'
import PropTypes from 'prop-types'

import { FormField, TextArea } from 'grommet'

export const TextAreaExpandable = ({
  name,
  onChange,
  minRows,
  maxRows,
  ...rest
}) => {
  const calculateRowCount = value => {
    const valueRowsCount = (value.match(/\n/g) || '').length + 1
    return valueRowsCount < minRows
      ? minRows
      : valueRowsCount > maxRows
        ? maxRows
        : valueRowsCount
  }

  const initRowCount = calculateRowCount(rest.value) // TODO: does not change row count when initialized with value
  const [rows, setRows] = useState(initRowCount)

  const changeRowCount = value => setRows(calculateRowCount(value))

  const onChangeHandler = (e) => {
    const { target: { value } } = e
    changeRowCount(value)
    onChange && onChange(e)
  }

  return (
    <FormField
      style={{ display: 'flex' }}
      plain
      resize='vertical'
      margin={{ horizontal: 'xxsmall' }}
      name={name}
      label={name}
      onChange={onChangeHandler}
      component={TextArea}
      rows={rows}
      {...rest}
    />
  )
}

TextAreaExpandable.propTypes = {
  name: PropTypes.string.isRequired,
  onChange: PropTypes.func,
  minRows: PropTypes.number,
  maxRows: PropTypes.number
}

TextAreaExpandable.defaultProps = {
  required: true,
  onChange: undefined,
  minRows: 2,
  maxRows: 10
}

The usage in the form:

<TextAreaExpandable
  name={name}
  placeholder={placeholder}
  value={value}
  onChange={onChange}
/>
0

There are 0 answers