Prompt
How do I build a dynamic survey in React?
Latest observation
Aug 27, 2026
OpenAI APIWeb search: off
A good way to build a dynamic survey in React is to make the survey data-driven: store the questions in a JSON-like config, render them from that config, and keep answers in component state.
1) Define your survey structure
Example config:
const surveyQuestions = [
{
id: "name",
type: "text",
label: "What is your name?",
required: true,
},
{
id: "age",
type: "number",
label: "How old are you?",
required: true,
},
{
id: "satisfaction",
type: "radio",
label: "How satisfied are you?",
options: ["Low", "Medium", "High"],
},
{
id: "feedback",
type: "textarea",
label: "Any additional feedback?",
},
];
2) Keep answers in state
Use a single object keyed by question id:
import React, { useState } from "react";
function Survey() {
const [answers, setAnswers] = useState({});
const handleChange = (id, value) => {
setAnswers((prev) => ({
...prev,
[id]: value,
}));
};
const handleSubmit = (e) => {
e.preventDefault();
console.log("Survey answers:", answers);
};
return (
<form onSubmit={handleSubmit}>
{surveyQuestions.map((q) => (
<div key={q.id} style={{ marginBottom: "16px" }}>
<label>
{q.label}
{q.required ? " *" : ""}
</label>
{q.type === "text" && (
<input
type="text"
value={answers[q.id] || ""}
onChange={(e) => handleChange(q.id, e.target.value)}
/>
)}
{q.type === "number" && (
<input
type="number"
value={answers[q.id] || ""}
onChange={(e) => handleChange(q.id, e.target.value)}
/>
)}
{q.type === "textarea" && (
<textarea
value={answers[q.id] || ""}
onChange={(e) => handleChange(q.id, e.target.value)}
/>
)}
{q.type === "radio" &&
q.options.map((option) => (
<label key={option} style={{ display: "block" }}>
<input
type="radio"
name={q.id}
value={option}
checked={answers[q.id] === option}
onChange={() => handleChange(q.id, option)}
/>
{option}
</label>
))}
</div>
))}
<button type="submit">Submit</button>
</form>
);
}
export default Survey;
3) Add conditional questions
If some questions should appear only when certain answers are chosen, add a showIf property:
{
id: "petName",
type: "text",
label: "What is your pet's name?",
showIf: (answers) => answers.hasPet === "Yes",
}
Then filter before rendering:
const visibleQuestions = surveyQuestions.filter(
(q) => !q.showIf || q.showIf(answers)
);
4) Add validation
You can validate required fields on submit:
const validate = () => {
const errors = {};
surveyQuestions.forEach((q) => {
if (q.required && !answers[q.id]) {
errors[q.id] = "This field is required";
}
});
return errors;
};
5) For larger surveys, use a form library
If the survey gets more complex, use:
- React Hook Form for performance and simple registration
- Formik for structured forms
- Yup or Zod for validation
React Hook Form is usually a strong choice for dynamic forms.
If you want, I can also show you:
- a fully working dynamic survey component,
- a version with conditional branching, or
- one using React Hook Form.