Dinesh Ghimire
Dinesh Ghimire

Reputation: 31

React js dynamic input field value to state

How to pass dynamic input field value to state as an array and update the value when user changes the input again?

Input field was generated by JSON data and in the state, we cannot define the initial value for all. Can anyone give some advice for this kind of problem?

this.state = { 
file:[{value1,value2}]
}; 

and input field is generated like

{this.state.language.map((item,index) =>
<div className="be-checkbox inline" key={index} >
 <input type="text"  onChange={this.handleChange.bind(this, index)} value={this.state.index} />
</div>
)}

Upvotes: 3

Views: 28717

Answers (3)

Vicheans
Vicheans

Reputation: 111

Using React Hooks:

const [data, setData] = useState({});
//create an onInputChange function for the inputs this way
const onInputChange = async e => {
  const {name, value} = e.target;
  //check to validate if entry is not a number
  if(isNaN(name)){
    data[name] = value;
    
    //somehow update data
    setData({...data})
  }
}

Upvotes: 2

Rex
Rex

Reputation: 376

Variable Inputs with JSON Values

You can build a model to store the new values in and two methods, one to handle new values and another for updating state. You can then call map() on the keys from your JSON data inside your array and produce an input for each entry.

class MyFormComponent extends React.Component {
    inputValues = new Map();

    onInputChange(evt, key){
        inputValues.set(key, evt.target.value);
    }

    updateState() {
        const update = inputValues.reduce((updater, value) => {
           return {...updater, value} // assuming value === {key: value} from your example, because {value, value} is not valid JSON
        }, {});

        this.setState({
            file: [JSON.stringify(update)]
        });
    }

    render(
       const keys = Object.keys(JSON.parse(this.state.file[0]))

       return keys.map(key => {
             // onChange will give you new values to your map model. 
            <input 
                type="text"
                key={key}
                onChange={eve => this.onInputChange(evt, key)}
            />
        });
    }   
}

Now call this.updateState() whenever you want to update the state with the current input values.

eg <input ... onBlur={this.updateState} />

Upvotes: 1

S.M. Shakil
S.M. Shakil

Reputation: 159

Add onChange and value in every input like below.

<input type="text" onChange={this.handleChange.bind(this, index)} value={this.state.index}/>

Add the function to be called

handleChange(name, e){
    var change = {};
    change[name] = e.target.value;
    this.setState(change);
  }

Upvotes: 5

Related Questions