Reputation: 35
I have manage to get it display all the items, so it display like this
Is there a way to display it only 1 item each time I'm pressing the next and previous button? I still don't know how to do it, and I can't find keyword to research about it.
Here is my code, can someone give me some examples, guides, or some codes to help me to understand more about it, thank you. What I'm thinking is create an array like [0->n], that's why I'm putting this.props.question into a state, when ever I click the next and previous button it'll go back and forth in an index, and it'll array the state, too, that's what I'm thinking in my head but I don't know how to write it or it's correctly or not...
import {Component} from 'react'
class QuizForm extends Component {
constructor(props){
super(props)
this.state={
quizs: [],
questions: [this.props.question],
}
}
render(){
const {next, previous, question} = this.props;
console.log(this.state.questions);
return(
<div className="column middle">
<div className="game-details-container">
<h1> Question : <span id="question-number"></span> / 10</h1>
</div>
<div className="game-quiz-container">
{/* <DisplayQuestion/> */}
{question}
<div className="game-options-container">
<span>
<input type="radio" id="option-one" name="option" className="radio" value="optionA" />
<label htmlFor="option-one" className="option" id="option-one-label">A Answer</label>
</span>
</div>
<div className="next-button-container">
<button onClick = {previous}>Previous Question</button>
<button onClick = {next}>Next Question</button>
</div>
</div>
</div>
);
}
}
Edit: The data of this.state.questions
Upvotes: 0
Views: 837
Reputation: 7156
It's quite simple.
step
variable's value is used go on prev and next question indexprevious
method: decrements the step counternext
method: increments the step counter
state = {
step: 0,
questions: [
{ id: 1, title: 'What is your name?' },
{ id: 2, title: 'What do you do?' },
{ id: 3, title: 'Where you from?' }
]
};
previous = () => {
if (this.state.step === 0) {
return; // should not go back after first question
}
this.setState({ step: this.state.step - 1 });
};
next = () => {
if (this.state.step === this.state.questions.length - 1) {
return; // should not go forward after last question
}
this.setState({ step: this.state.step + 1 });
};
render() {
return (
<>
Question: {this.state.questions[this.state.step].title}
<div style={{ display: 'flex', marginTop: 10 }}>
<button onClick={this.previous}>Previous</button>
<button onClick={this.next}>Next</button>
</div>
</>
);
}
Upvotes: 1