I want to move through the contents of a JSON file with buttons.
This is the basic structure of my JSON:
[
{
"page": "1",
"required": "true",
"question": "lorem ipsum",
},
{
"page": "2",
"required": "true",
"question": "lorem ipsum dolor",
}
]
I'm building a multi-step form and I want to get the questions from this JSON. Is there any way for me to have a Next
button, that moves one index forward in the JSON file, and displays the info in that index? The page
identifier is unique to every object.
I'm new to React, so any explanations will be appreciated!
CodePudding user response:
In my opinion, in order to iterate through the questions of your JSON, you'll first need to parse it by using JSON.parse()
(documentation).
So per exemple, let's say your component looks like this :
function Form() {
[questions, setQuestions] = JSON.parse(your_json);
[currentQuestion, setCurrentQuestion] = 0;
function nextQuestion {
setCurrentQuestion = currentQuestion 1;
}
return (
<div>
<label>{{ questions[currentQuestion].question }}</label>
<input type="text" />
<button onclick={ nextQuestion }>Next Question</button>
</div>
);
}
By doing this, you'll parse the JSON text, changing it to an object format, and make you being able to call any value. Then we have a counter and we will be able to change it's value by calling setCurrentQuestion
. The method nextQuestion()
does exactly this.
Then, in our JSX, we can display the question based on it's position in the JSON, and go to the next question by clicking the button. React will react to the value change by itself and then, change the question value automatically.
I hope that my answer help while being clear enough and I didn't do any mistake typing it ^^