Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I programatically fill input field value with React?

I have a modal with some input fields. I can easily pass the data automatically with the user typing an input, using onChange function in the input field, as

<Input onChange={this.props.store.handleCategoryChange} type="text" />

and .. (Using a mobx store, irellevant though)

@observable categoryValue;
@action handleCategoryChange = (e, data) => {
    this.categoryValue = data.value;
    e.preventDefault();
};

However, I want to add a function where the user can pre-fill this with information elsewhere in the application. I have the data to pre-fill the input fields with, but I can't figure out how do actually input it programatically, without the user doing it?

I need to invoke the above handleCategoryChange function. But my variable would be equal to data.value .. Which presents a problem! Invoking this function by myself isn't possible, because I won't have the event e nor a value called data.value as I will "just" pass in a variable by itself.

What's the right way to programatically fill an input field automatically in React, using variables elsewhere? I need to invoke the onChange function somehow, but the input values will be different..

like image 305
cbll Avatar asked Jun 21 '17 08:06

cbll


Video Answer


3 Answers

Use controlled component for this situation, define a value property of input element like this:

<Input value={variable_name} ....

Whenever you will update that variable, automatically that value will get populated in input element.

Now you can populate some default value by assigning a value to variable_name and user can update that value by onChange function.

As per DOC:

An input form element whose value is controlled by React in this way is called a "controlled component".

like image 115
Mayank Shukla Avatar answered Oct 19 '22 03:10

Mayank Shukla


Pass in the value property for input:

<input type="text" value={this.state.value} onChange={(e) => {this.setState({value: e.target.value })}/>
like image 22
Ashh Avatar answered Oct 19 '22 04:10

Ashh


you can use the controlled component and pass the value to it.

<input type="text" value{this.state.value} 
       onChange={()=>  {this.setState({value:e.target.value })}}
like image 2
RAVINDER MAHAJAN Avatar answered Oct 19 '22 05:10

RAVINDER MAHAJAN