Sha Li
Sha Li

Reputation: 445

React save the value of current state and make it unchangeable

I am new to React and I have a problem considering saving the value of current state. I am not sure if it is possible.

To summarise, I have build up a function which returns a HTML element as below. The idea is to save a div on each click.

createQuestion(){
        let CurrentQuestion=this.state.freetextinput;
        return this.state.values.map((el, i) => 
         <div key={i} className="QuestionBox">
            {CurrentQuestion}
         </div>          
        )
    }

The value of freetextinput changes on each click. The idea is to save all the value of freetextinput. Say, the values of freetextinput are 1, 2, 3. I would like to have all of the three values:

1
2
3

However, I only get something like this:

3
3
3

I wonder, if there is a way to save/store the value of this.state.freetextinput, such that I can get all the three values.

Upvotes: 2

Views: 609

Answers (3)

Geeky
Geeky

Reputation: 7496

Save every input of free text input into an array, that way you would get access to all the values:

You can check this code sandbox: https://codesandbox.io/s/j835121kv

Upvotes: 2

stever
stever

Reputation: 1241

The new question needs to be pushed into an array before it can be mapped. Might something like this work for you?

var savedQuestions = []

createQuestion(q){        
  savedQuestions.push(q)
  this.setState({savedQuestions: savedQuestions}, () => {
    var questionElements = this.state.savedQuestions.map((el, i) => 
     <div key={i} className="QuestionBox">
        {el}
     </div>          
    )
    })
    return questionElements
}

Upvotes: 3

Treycos
Treycos

Reputation: 7492

You should map this.state.freetextinput directly :

Since freetextinput is a string, you will need to convert it to an array first using split

createQuestion(){
    return this.state.freetextinput.split(', ').map(el =>
        <div key={el} className="QuestionBox">
            {el}
        </div>
    )
}

This will work if your string looks like : "1, 2, 3" If your string is "123" then use split('') instead of split(', ')

Upvotes: 1

Related Questions