Reputation: 187379
I'm using react-jsonschema-form to create a form from a JSON schema. In this JSFiddle example, I've created a form that consists of a single <input type="file">
field.
An instance of a FileWidget component is used to render this field, and as you can see in the source code, this stores a ref to the <input>
element in this.inputRef
.
I would like to use this ref to add additional attributes to the input field, but I can't figure out how to access the ref from the componentDidMount
method of MyForm
?
The source code of the component in the JSFiddle example is:
class MyForm extends React.Component {
constructor(props) {
super(props);
this.uiSchema = {};
this.schema = {
"title": "Files",
"type": "object",
"properties": {
"file": {
"type": "string",
"format": "data-url",
"title": "Single file"
},
}
}
};
componentDidMount() {
// How can I get access to the FileWidget's inputRef property here?
}
render() {
return (
<Form
schema={this.schema}
uiSchema={this.uiSchema}
liveValidate />
)
}
};
Upvotes: 1
Views: 1169
Reputation: 11270
You can import and use FileWidget
from the same library to get a ref on it:
import FileWidget from 'react-jsonschema-form/lib/components/widgets/FileWidget'
constructor(props) {
...
this.widgets = {
FileWidget: (props) => (
<FileWidget
{...props}
ref={ref => {
this.fileWidget = ref;
}}
/>
)
};
}
componentDidMount() {
console.log(this.fileWidget.inputRef);
}
<Form widgets={this.widgets} ... />
This is not a very intuitive way for a library to expose an internal ref. It should have been:
<input
ref={ref => {
if (this.props.setInputRef) {
this.props.setInputRef(ref);
}
}}
/>
Then you could get inputRef
with
<FileWidget setInputRef={ref => { this.inputRef = ref } ... />
Upvotes: 1