3

I have custom component Slider for Formio. Function attachReact() is attaching my custom component inside element provided by Formio. After attaching is done I am supposed to get an instance for that component from ReactDOM.render() returned right away but I am not. Later that instance is used by Formio to change field values which I need.

How can I make sure I get an instance from ReactDOM returned right away? I realise that feature will be removed in future from React but I still need it while Formio is using it.

import { ReactComponent } from "@formio/react";
import React from "react";
import ReactDOM from "react-dom";
import settingsForm from "./Slider.settingsForm";

class SliderCustomComp extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      value: props.value,
    };
  }

  setValue = (v) => {
    this.setState({ value: v }, () => this.props.onChange(this.state.value));
  };

  render() {
    return (
      <div className="w-full" id="custcomp">
        <input
          className="w-full focus:outline-none"
          type="range"
          min={this.props.component.minRange}
          max={this.props.component.maxRange}
          value={this.state.value}
          onChange={(e) => {
            this.setValue(e.target.value);
          }}
        />
        <span>{this.state.value}</span>
      </div>
    );
  }
}

export default class Slider extends ReactComponent {
  constructor(component, options, data) {
    super(component, options, data);
  }

  static schema() {
    return ReactComponent.schema({
      type: "sliderCustomComp",
      label: "Default Label",
    });
  }
  static editForm = settingsForm;

  attachReact(element) {
    console.log(element);
    const instance = ReactDOM.render(
      <SliderCustomComp
        component={this.component} // These are the component settings if you want to use them to render the component.
        value={this.dataValue} // The starting value of the component.
        onChange={this.updateValue} // The onChange event to call when the value changes.}
      />,
      element
    );

    console.log("instance in attachReact", instance);

    return instance;
  } 
}
 
rmlockerd
  • 3,776
  • 2
  • 15
  • 25

1 Answers1

0

Use prop ref to get the instance:

const instanceRef = React.createRef();
ReactDOM.render(
  <SliderCustomComp
    ref={instanceRef}
    component={this.component} // These are the component settings if you want to use them to render the component.
    value={this.dataValue} // The starting value of the component.
    onChange={this.updateValue} // The onChange event to call when the value changes.}
  />,
  element
);
const instance = instanceRef.current;
mareolan
  • 123
  • 1
  • 6