Create a Class to Modify Component State

(Adam) #1

Hi all,

So I am currently playing around with a more efficient way to handle how our app is populated with questions. I am curious as to how I could create a generic javascript class that could manipulate a component’s state, but also do more. So for example… We have a bunch of different question types (yes/no, multiple choice, dropdown select, etc.) and when we render those questions they need to be handle differently for the different question types. There are also different things that need to be done like display the result, clear question answer, etc. So what I wanted to do was create like an “interface” that could make it easy to just object.renderQuestion(), object.displayResult(), object.clearQuestion() for each question type and then the classes themselves would handle doing the specific tasks it takes to do that for each question type. Pretty simple interface.

My issue right now is I understand that in order to modify the state of a child component you need to set the state in the parent, pass through props to the child, and then update the state in the parent and it will update the child. This works great, but what if I don’t have a state in the parent because it is a generic javascript object. Here is an example:

  export default class BoolQuestionObject {
  question: object;

  constructor(quest) {
    this.question = quest;

  handleAnswer(question, answer) {
    question.Answer = answer;


 displayResult() {

  renderQuestion() {
    return (
      <View key={this.state.question.Name}>
          onButtonPress={this.handleAnswer.bind(this,this.state.question)} />


So when I am in the main component then I will call object.RenderQuestion for this object. It returns the BoolQuestion component just fine, but the issue is when the handleAnswer function gets hit (when a button is pressed on the child component) then it will update the question object which is good, but that does not go back to the child component to update the state of the child component.

So my question is… Is this a good approach? I find we are repeating a lot of code simply because we need to handle different types differently which to me is a perfect example of implementing an interface design, but maybe this doesn’t work well with React? If this approach is valid… How can I update the child state in this non-component parent class (so there is no setState function).