Reputation: 596
From the step 1 dropdown if the user is picking one after submit redirect it to step2schema, and if he is picking two redirect him after submit to step3schema. Here is the jsfiddle (check my link):
const Form = JSONSchemaForm.default;
const step1schema = {
title: "Step 1",
type: "number",
enum: [1, 2],
enumNames: ["one", "two"]
};
const step2schema = {
title: "Step 2",
type: "object",
required: ["age"],
properties: {
age: {type: "integer"}
}
};
const step3schema = {
title: "Step 3",
type: "object",
required: ["number"],
properties: {
number: {type: "integer"}
}
};
class App extends React.Component {
constructor(props) {
super(props);
this.state = {step: 1, formData: {}};
}
onSubmit = ({formData}) => {
if (this.state.step === 1) {
this.setState({
step: 2,
formData: {
...this.state.formData,
...formData
},
});
} else {
alert("You submitted " + JSON.stringify(formData, null, 2));
}
}
render() {
return (
<Form
schema={this.state.step === 1 ? step1schema : step2schema}
onSubmit={this.onSubmit}
formData={this.state.formData}/>
);
}
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://npmcdn.com/[email protected]/dist/react-jsonschema-form.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
https://jsfiddle.net/bogdanul11/sn4bnw9h/29/
Here is the lib I used for documentation: https://github.com/mozilla-services/react-jsonschema-form
What I need to change in order to have my desired behavoir ?
Upvotes: 0
Views: 1020
Reputation: 4636
Replace your state to this first
this.state = {step: 0, formData: {}};
Then replace your onSubmit
logic to
onSubmit = ({formData}) => {
const submitted = formData;
this.setState({
step: submitted,
formData: {
...this.state.formData,
...formData
},
})
}
Finally replace your schema logic
schema={this.state.step === 0 ? step1schema : ( this.state.step === 1 ? step2schema : step3schema)}
the schema selecting ternary operation is what we call a compound ternary operation. If state.step
is 0 , we select step1schema... if not a new selection statement ( this.state.step === 1 ? step2schema : step3schema)
is run; in which if step is 1, step2schema is selected and for anything else step3schema.
Lets say you have more than 3 schemas and you want to access them. For that you will have to define the schemas in an array and access them using the index.
schemaArray = [ {
// schema1 here
} , {
// schema2 here
} , {
// schema3 here
}, {
// schema4 here
}, {
....
}]
Now your schema selecting you will have to use
schema = { schemaArray[ this.state.step ] }
Upvotes: 1