Repository navigation
Function-calling React Component #15
Replies: 6 comments 1 reply
Back-end support to the componentNow let's look zoom out to include the back-end support for such a component. Note that the diagrams shown below are abstract data/functional relationships.
We give the implementation-free view precisely to help the design be free and separate from those concerns. Simple pipelineA Implementation notes:
We discussed the some of the dynamic/static choices in the implementation notes, but not the frontend/backend choices.
Adding configsIn this diagram, we add optional Note that again, there's no indication if, say, the
Adding conventionsFinally, if the configs contain a lot of parameters, it may be burdensome to have to fully express them anytime we'd want to do something else than the default. In that case, we can use the convention/configuration design, whereby:
The diagram below makes this design explicit.
|
|
Sathish's feedback and doubts: "as far as i understood that
Also the Back-end support this part will be taken care by you right? here 2 things
from Thor's word i understood this much only Valentin! |
|
Some content from the original post... Technology searchReactJS frameworks for formsThese are a few frameworks we could look into:
react-jsonschema-formThe most promising one, for our purposes, seems to be
Example (not complete) function to convert func to json-schemaimport inspect
from typing import Callable
def function_to_json_schema(func: Callable):
# Fetch function metadata
sig = inspect.signature(func)
parameters = sig.parameters
# Start building the JSON schema
schema = {
"title": func.__name__,
"type": "object",
"properties": {},
"required": []
}
# Build the schema for each parameter
for name, param in parameters.items():
# Set the type based on the annotation
if param.annotation is int:
field = {"type": "integer"}
elif param.annotation is float:
field = {"type": "number"}
elif param.annotation is bool:
field = {"type": "boolean"}
else:
field = {"type": "string"}
# If there's a default value, add it to the schema
if param.default is not inspect.Parameter.empty:
field["default"] = param.default
else:
schema["required"].append(name)
# Add the field to the schema
schema["properties"][name] = field
return schemaExample of code to inspire React componentimport React, { useState, useEffect } from 'react';
import Form from "@rjsf/core";
import axios from 'axios';
const MyForm = () => {
const [selectedFunction, setSelectedFunction] = useState(null);
const [functions, setFunctions] = useState([]);
const [schema, setSchema] = useState(null);
const [result, setResult] = useState(null);
// Fetch the list of functions when the component mounts
useEffect(() => {
axios.get('/api/functions')
.then(response => {
setFunctions(response.data);
});
}, []);
// Fetch the schema whenever the selected function changes
useEffect(() => {
if (selectedFunction) {
axios.get(`/api/schemas/${selectedFunction}`)
.then(response => {
setSchema(response.data);
});
}
}, [selectedFunction]);
// Handle form submission
const onSubmit = ({formData}) => {
axios.post(`/api/call/${selectedFunction}`, formData)
.then(response => {
setResult(response.data);
});
};
return (
<div>
<h1>Select a function</h1>
<select value={selectedFunction} onChange={e => setSelectedFunction(e.target.value)}>
{functions.map(func => (
<option key={func} value={func}>{func}</option>
))}
</select>
{schema && (
<div>
<h1>Fill the form</h1>
<Form schema={schema} onSubmit={onSubmit} />
</div>
)}
{result && (
<div>
<h1>Result</h1>
<pre>{JSON.stringify(result, null, 2)}</pre>
</div>
)}
</div>
);
};
export default MyForm; |
In react-json-schema-form, how can I source a select box from an API call?In Here's a basic example to demonstrate how you can achieve this: Step 1: Fetch Data from APIFirst, you'll need to fetch the data from the API. You can use import React, { useEffect, useState } from 'react';
import Form from 'react-jsonschema-form';
const App = () => {
const [formData, setFormData] = useState({});
const [selectOptions, setSelectOptions] = useState([]);
useEffect(() => {
// Fetch data from API
fetch('https://api.example.com/items')
.then((response) => response.json())
.then((data) => {
// Transform data to { label, value } format if needed
const options = data.map((item) => ({
label: item.name,
value: item.id,
}));
setSelectOptions(options);
});
}, []);
// ...
}Step 2: Update Schema or UI SchemaAfter fetching the data, update the // JSON Schema
const schema = {
type: 'object',
properties: {
item: {
type: 'string',
enum: selectOptions.map((option) => option.value),
enumNames: selectOptions.map((option) => option.label),
},
},
};
// UI Schema
const uiSchema = {
item: {
'ui:widget': 'select',
},
};Step 3: Render the FormFinally, render the form using the updated schema and UI schema. return (
<Form
schema={schema}
uiSchema={uiSchema}
formData={formData}
onChange={(e) => setFormData(e.formData)}
/>
);Putting it all together: import React, { useEffect, useState } from 'react';
import Form from 'react-jsonschema-form';
const App = () => {
const [formData, setFormData] = useState({});
const [selectOptions, setSelectOptions] = useState([]);
useEffect(() => {
fetch('https://api.example.com/items')
.then((response) => response.json())
.then((data) => {
const options = data.map((item) => ({
label: item.name,
value: item.id,
}));
setSelectOptions(options);
});
}, []);
const schema = {
type: 'object',
properties: {
item: {
type: 'string',
enum: selectOptions.map((option) => option.value),
enumNames: selectOptions.map((option) => option.label),
},
},
};
const uiSchema = {
item: {
'ui:widget': 'select',
},
};
return (
<Form
schema={schema}
uiSchema={uiSchema}
formData={formData}
onChange={(e) => setFormData(e.formData)}
/>
);
};
export default App;This example demonstrates how to populate a |
Can I map some fields to custom input JS elements in react-jsonschema-form?Yes, you can map fields to custom input elements in Custom WidgetsYou can create custom widgets and pass them to the Here's an example of a custom text input widget: const CustomTextInput = (props) => {
return (
<input
type="text"
value={props.value}
required={props.required}
onChange={(event) => props.onChange(event.target.value)}
/>
);
};To use this custom widget, you would pass it in the import Form from 'react-jsonschema-form';
const widgets = {
customTextInput: CustomTextInput,
};
<Form schema={schema} uiSchema={uiSchema} widgets={widgets} />And in your UI schema, you would specify that you want to use this custom widget: const uiSchema = {
textField: {
"ui:widget": "customTextInput",
},
};Custom FieldsSimilarly, you can create custom fields. A custom field is a bit more involved than a custom widget because it allows you to control the entire layout of a field, including its label, the input element, and any validation messages. Here's an example of a custom field: const CustomField = (props) => {
return (
<div>
<label>{props.label}</label>
<input
type="text"
value={props.formData}
onChange={(event) => props.onChange(event.target.value)}
/>
{props.rawErrors && (
<ul>
{props.rawErrors.map((error, i) => (
<li key={i}>{error}</li>
))}
</ul>
)}
</div>
);
};To use this custom field, you would pass it in the import Form from 'react-jsonschema-form';
const fields = {
customField: CustomField,
};
<Form schema={schema} uiSchema={uiSchema} fields={fields} />And in your UI schema, you would specify that you want to use this custom field: const uiSchema = {
textField: {
"ui:field": "customField",
},
};By using custom widgets and fields, you can have complete control over the rendering of inputs in |




Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Objective
A reusable react component that essentially calls a remote python function.
This component could have all kinds of parameters to control different (view and control) aspects of the component, but the only two required parameters are:
Though this itself could be parametrized, we'll say that the "user input" view will be for now a form.
Therefore, we look into react frameworks that will help us:
Proposed Steps
Useful links
All reactions