Adding ref to cloneElement to set focus to cloneElement

I have not used cloned elements before, but now I'm trying to create a button that, when pressed, opens an input window of the appropriate type and, to a decisive extent, focuses on the input field. It seems that I mainly work, except that it does not focus (I get a console error that _this.refs.content.focus is not a function). I tried reading the documentation and other questions, but I will not go further. Any help appreciated

  getInitialState() {
    return {
      isEditing: false,
      .....
    };
  },

  _onEdit() {
    if (this.state.isEditing) return;
    this.setState({
      isEditing: true,
      editedValue: this.props.value,
    }, () => {
      console.dir(this.refs);
      this.refs.content.focus();
    });
  },

  .....

  render() {
    .....
    // button clicked
    if (this.state.isEditing) {

      return React.cloneElement(
        this.props.children[0], {
          onBlur: this.onBlur,
          value: this.state.editedValue,
          onChange: this.onChange,
          ref: "content",
        }
      );

    } else {

      const child = this.props.children[1];

      // Editable but in read mode - display clickable button
      return pug`
        button.btn-block.btn-editable(
          onClick=this._onEdit,
          type='button',
        )= React.cloneElement(child, {}, this.state.editedValue || (child.props.children || ""))
      `;
    }
  },
+4
source share

Source: https://habr.com/ru/post/1655196/


All Articles