Как передать React.createRef компоненте Textarea?

У меня есть компонент Textarea

import React from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';

import './textarea.scss';

export default function Textarea(props) {
  const {
    className,
    placeholder,
    onChange,
    ref,
    ...restProps
  } = props;

  return (
    <textarea
      className={classNames('textarea', className)}
      placeholder={placeholder}
      onChange={onChange}
      ref={ref}
      {...restProps}
    />
  );
}

Я хочу передать ему ref, чтобы можно было вывести вводимый текст, но при передаче компоненту Textarea ссылки ref, он видит в ней undefined.

import React from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';

import Button from '../../components/button';
import Textarea from '../../components/textarea';

import './profile.scss';

export default function Profile(props) {
  const {
    className,
    state
  } = props;

  const addPostElement = React.createRef();

  const addPost = () => {
    alert(addPostElement.current.value);
  }

  return (
      <div
        className={classNames('profile', className)}
      >
          <form className="profile__add-post">
            <Textarea
              className="profile__add-post-input"
              placeholder="What's happening?"
              ref={addPostElement}
            />
            <Button
              className="profile__add-post-button"
              caption="Add post"
              onClick={addPost}
            />
          </form>
        </div>
</div>
  );
}

Если использовать стандартный textarea в форме, то все работает. Подскажите пожалуйста, как я могу передать ref конкретно самой компоненте.


Ответы (1 шт):

Автор решения: Vasily

Это можно сделать с помощью React.forwardRef:

const Textarea = React.forwardRef((props, ref) => (
  <textarea ref={ref} />
))
→ Ссылка