I’m working on a dynamic form where people can create questions for a survey.
The main form allows Questions to be added, and each question may have 1:N conditions and answers added to it.
The main template looks like this:
import React, { useState } from "react";
import Question from 'components/templates/question';
import { Button, Form } from 'react-bootstrap';
const Templates = () => {
const [questions, setQuestions] = useState([Question()]);
const increase = () => {
setQuestions([...questions, Question()]);
};
return (
<form>
{questions.map((component, index) => (
<React.Fragment key={index}>
{ component }
</React.Fragment>
))}
<Button variant='success' onClick={increase}> + </Button>
</form>
);
};
And the Questions with contain incrementable, repeatable conditions looks like this:
import React, { useState } from "react";
import { Button, Card, Form } from 'react-bootstrap';
import Condition from './condition';
const Question = () => {
const [conditions, setConditions] = useState([Condition()]);
const increaseC = () => {
setConditions([...conditions, Condition()]);
};
return (
<Card className="mb-4">
<Card.Body>
<Form.Group className="mb-3" controlId="questionTitle">
<Form.Label>Question Title</Form.Label>
<Form.Control type="text" placeholder="What is a simple name for this data point?" />
</Form.Group>
<Form.Group className="mb-3" controlId="questionDescription">
<Form.Label>Question Description</Form.Label>
<Form.Control type="text" placeholder="What are you looking for?" />
</Form.Group>
<h5 class="card-title">Conditions</h5>
<h6 class="card-subtitle text-muted">Are there conditions for when this text is displayed?</h6>
{conditions.map((component, index) => (
<React.Fragment key={index}>
{ component }
</React.Fragment>
))}
<br />
<Button variant='outline-success' size="sm" onClick={increaseC}>+</Button>
</Card.Body>
</Card>
);
}
export default Question;
As you can imagine, this does not work. I’ve seen passing arguments between components, but for the life of me I cannot figure out how to have multiple states that map component collections.