Reputation: 3
I have online exam project and a component for showing the question and a component for the button of all question and a parent component who is calling rest component
import React from 'react'
import Question from './Question';
class Exam extends React.Component{
constructor(){
super();
this.state={
current_question:"one"
}
this.changeQuestion=this.changeQuestion.bind(this)
}
changeQuestion(){
this.setState({current_question:'two'})
}
render(){
return (
<div>
<Question question={this.state.current_question}/>
<QuestionButton changeQuestion={this.changeQuestion} />
</div>
)
}
}
class QuestionButton extends React.Component{
render(){
return(
<button onClick={this.props.changeQuestion}>Click Me</button>
)
}
}
export default Exam;
this is my parent and button component
import React from 'react';
class Question extends React.Component{
constructor(props){
super(props);
this.state={
questions:{
one:{
question:"What is html full fomr",
options:{
a:"hyper text markup language",
b:"hyper text model language"
},
answer:"hyper text markup language",
submit:"not",
submited_answer:""
},
two:{
question:"this is question two",
options:{
a:"hyper text markup language",
b:"hyper text model language"
},
answer:"hyper text markup language",
submit:"not",
submited_answer:""
}
},
show_question:this.props.question
}
console.log(this.props)
}
render(){
let question_id=this.state.show_question
let object=this.state.questions
return object[question_id].question
}
}
export default Question
when i click on the button i want to show the second question. my question component state is getting updated as two but not showing the second question
Upvotes: 0
Views: 39
Reputation: 1336
Try like this.
import React from 'react';
class Question extends React.Component{
constructor(props){
super(props);
this.state={
...
show_question:this.props.question // maybe this variable doesn't need
}
console.log(this.props)
}
render(){
const { question } = this.props; // props change, because it contain parent's state
let object=this.state.questions
return object[question].question
}
}
export default Question
Upvotes: 1
Reputation: 19947
class Question extends React.Component{
constructor(props){
super(props);
this.state={
// ...
// this line is utterly unnecessary, remove it:
// show_question: this.props.question
}
}
render(){
// this line does the trick:
let question_id = this.props.question
let object=this.state.questions
return object[question_id].question
}
}
export default Question
Upvotes: 1