Thursday, June 6, 2024
 Popular · Latest · Hot · Upcoming
123
rated 0 times [  124] [ 1]  / answers: 1 / hits: 19830  / 7 Years ago, wed, april 12, 2017, 12:00:00

I am trying to add dynamic key/value pair to an initial object with the appendInput() function.



Initial object:



constructor(props) {
super(props);
this.state = {
milestonesValues : {
milestone0: dssdsad,
milestone1: ,
milestone2: ,
milestone3: ,
}
};


}



The render method:



render(){
return(
<div>
<main className=content>
<form onSubmit={this.onSubmit}>
<div className=input-wrap>
<label>{'What are the basic steps?'}
{Object.keys(this.state.milestonesValues).map( (milestone, index) =>
<input
key={milestone}
placeholder={`${index+1}.` }
type=text
name={milestone}
value={this.state.milestonesValues[milestone]}
onChange={this.handleInputChange} />
)}
</label>
<button onClick={ () => this.appendInput() }>
{+ ADD MILESTONE}
</button>
</div>
</form>
</main>
</div>
);


appendInput() function:



  appendInput() {
var objectSize = Object.keys(this.state.milestonesValues).length;
var newInput = `milestone${objectSize}: ,`;

console.log(newInput);
this.setState({
milestonesValues: this.state.milestonesValues.concat([newInput])
});


}



and I just can't add the new generated key/value to that initial object.



Can someone help, please?


More From » reactjs

 Answers
5

You can accomplish what you want using computed expression (I'm not really sure if you are trying to do that already). So your appendInput function should look something like this:





appendInput() {
var objectSize = Object.keys(this.state.milestonesValues).length;
var newInput = Object.assign({},
this.state.milestonesValues, {['milestone'+ objectSize]: ''});
this.setState({
milestonesValues: newInput)
});
}




[#58168] Tuesday, April 11, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
annaliese

Total Points: 86
Total Questions: 97
Total Answers: 107

Location: Dominican Republic
Member since Sun, Sep 4, 2022
2 Years ago
annaliese questions
;