Home > Enterprise >  How to forward a ref from parent to child in reactjs
How to forward a ref from parent to child in reactjs

Time:10-18

I have the following scenario, what should I do so the attachment field existing in the child component can be accessible from the parent component

class ServiceDeskCustomerCreate extends Component {
  constructor(props, context) {
    super(props, context);
    this.AttachmentRef = React.createRef();
  }
  handleSubmit = async (event) => {
    var jsonresp = await IssueHelper.CreateCustomerRequest(
      userid,
      event,
      this.state.requestTypeFields,
      this.AttachmentRef.current, // here the `AttachmentRef` is always null
      this.MessageInfoRef.current,
      this.props.history,
      this.state.emailTokenData,
      lang
    );
  };
  render() {
    return (
      <>
        <CreateSystemFields
          FieldKey={key}
          elem={elem}
          bodyItemsStyle={bodyItemsStyle}
          labelAppearance={labelAppearance}
          emailSubject={this.state.emailSubject}
          editorValue={this.state.editorValue}
          onEditorSave={this.onEditorSave}
          EditorCoreRef={this.EditorCoreRef}
          onEditorSaveEnvironment={this.onEditorSaveEnvironment}
          files={this.state.files}
          saveCurrentFiles={this.saveCurrentFiles}
          AttachmentRef={this.AttachmentRef}
        />
        <Button
          appearance={this.state.buttonAppearene}
          style={{ display: "inline-block" }}
          type="submit"
          isDisabled={this.state.isSubmitButtonDisabled}
          isLoading={this.state.isSubmitButtonLoading}
          onClick={() => {
            this.handleSubmit();
          }}
        />
      </>
    );
  }
}

class CreateSystemFields extends Component {
  render() {
    <AttachmentField
      currentFiles={this.props.files}
      maxfileUploadSize={value.maxfileUploadSize}
      parentCallback={this.props.saveCurrentFiles}
      label={value.name}
      ref={this.props.AttachmentRef}
    />;
  }
}

CodePudding user response:

Ok,

Here is a really simple example, it basically changes the child's innerText from the parent, but please note don't do something like this in a real React as that is something that doesn't require it, but it just makes the demo nice and simple.

Basically all you do is send an object to the child via props, the child can then update the object, and now the parent has access.

eg..

function Parent() {
  const store = {};
  return <div>
    <button
      onClick={() => {
        store.ref.current.innerText = 'Hello @ '   new Date();
      }} 
    >
       Change Child Text using ref<br/>
       <b>ps. Don't do this in a real APP :}</b>
    </button>
    <Child store={store}/>
  </div>
}

function Child({store}) {
  const ref = React.createRef();
  store.ref = ref;
  return <div ref={ref}>Hello</div>
}


ReactDOM.render(<Parent/>, document.querySelector('#mount'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="mount"></div>

  • Related