React-jsonschema-form: withTheme does not forward ref

Created on 13 Aug 2019  路  8Comments  路  Source: rjsf-team/react-jsonschema-form

Description

The withTheme HOC is not forwarding it's ref. Therefore it is e.g. not possible to submit a form programmatically. React.forwardRef is available from 16.3.0, an implementation would look like this:

import React, { forwardRef } from "react";
import PropTypes from "prop-types";
import Form from "./";

function withTheme(themeProps) {
  return forwardRef(({ fields, widgets, ...directProps }, ref) => (
    <Form
      {...themeProps}
      {...directProps}
      fields={{ ...themeProps.fields, ...fields }}
      widgets={{ ...themeProps.widgets, ...widgets }}
      ref={ref}
    />
  ));
}

withTheme.propTypes = {
  widgets: PropTypes.object,
  fields: PropTypes.object,
};

export default withTheme;

For now I will use my own HOC instead of withTheme. Please fix this as soon as you bump the React peer version. I will happily provide an PR then, testcase also kinda done:

  it('should forward the ref', () => {
    let ref = undefined;
    const schema = {};
    const uiSchema = {};

    createComponent(withTheme({ ref: (form) => ref = form }), {
      schema,
      uiSchema,
    });

    expect(ref.submit).to.exist();
  });
breaking change

All 8 comments

@zepatrik thanks for your report. Feel free to make a PR to the v2 branch, which will have an upgraded version of react (at least when #1408 passes CI). I've included more details on the v2 roadmap at #1409.

@zepatrik could you plz, maybe, recommend some workaround of how to do programmatic submit until your PR is merged ?

Hey @andrew-oreshko , I also encountered this issue. For now, and as a temporary fix, I created my own withTheme HOC using the code provided by @zepatrik. Beware that this will only work if your project uses react version 16.3.0 or higher.

@zepatrik could you plz, maybe, recommend some workaround of how to do programmatic submit until your PR is merged ?

Maybe a bit late since they're going to release a fix for this soon, but it may help someone with an older version:

      let submitButton;
      [...]
      <FormWithTheme [...] >
        <Button style={{ visibility: 'hidden' }} ref={(ref) => { submitButton = ref; }} type="submit">hidden</Button>
      </FormWithTheme>
      <Button onClick={() => submitButton.click()}>Custom submit</Button>

So was a fix actually released for this?

It appears to have been merged with #1498, however my TypeScript tells me I cannot pass a ref prop into a Form that comes out of withTheme.

@jorisw pr is opened

@zepatrik v2 and above actually export types directly in this repository (https://github.com/rjsf-team/react-jsonschema-form/blob/master/packages/core/index.d.ts) -- could you make a PR to update that file?

I was actually searching for but could not find the types for v2, thanks

Was this page helpful?
0 / 5 - 0 ratings