'How to set a value to nested json schema in react?
I am new to javascript and JSON. Its almost 6 hours I am looking after a solution but couldn't find the correct one.
The problem is the default value of JSON schema can't change. Here is the code I have with codesandbox.
import "./styles.css";
import { useState } from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import MaterialJsonSchemaForm from "react-jsonschema-form-material-ui";
const schema = {
title: "Dynamic component",
description: "A simple form with input component",
type: "object",
properties: {
firstName: {
type: "string",
title: "Example input",
default: ""
}
}
};
const MetaDataExtender = ({ schema, uiSchema, onSubmit }) => {
const [formDataState, setFormData] = useState({});
const handleFormChange = ({ formData }) => {
setFormData(formData);
};
const handleSubmit = (value, callback) => {
onSubmit(value, callback);
};
const handleCancel = () => {};
return (
<MaterialJsonSchemaForm
schema={schema}
uiSchema={uiSchema}
formData={formDataState}
onCancel={handleCancel}
onSubmit={handleSubmit}
onChange={handleFormChange}
/>
);
};
const Example = () => {
const [data, setData] = useState({ formData: { firstName: "" } });
const handleSubmit = (data) => {
console.log("Submit value", data);
setData(data);
};
return (
<MetaDataExtender
key={"Example"}
schema={schema}
uiSchema={data.uiSchema || {}}
formData={data.formData}
onSubmit={handleSubmit}
onChange={({ formData }) => setData({ formData })}
/>
);
};
const GetValue = () => {
const [mydata, setMydata] = useState({
schema: { properties: { firstName: "sds" } }
});
setMydata(mydata);
};
export default function App() {
return (
<Router>
<div className="App">
<Switch>
<Route path="/">
<Example />
</Route>
</Switch>
<button type="button" onClick={() => GetValue()}>
Enter
</button>
</div>
</Router>
);
}
When user clicks enter the value of JSON schema (firstname) can't change and when I click cancel it doesn't disappear if I mutate state directly. Do you have any solution? I just want to update firstname when user click "enter" button.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
