Wednesday, April 26, 2017

Set React Input Field Value from JavaScript or JQuery

Leave a Comment

How can you programmatically set the value of an input field generated by React, either with vanilla JS or JQuery?

I've tried the following and nothing seems to work.

$(obj).val('abc'); $(obj).attr('value', 'abc'); $(obj).keydown(); $(obj).keypress(); $(obj).keyup(); $(obj).blur(); $(obj).change(); $(obj).focus(); 

I've also tried to simulate keyPress (as suggested here) events but it doesn't seem to work either.

simulateKeyPresses (characters, ...args) {   for (let i = 0; i < characters.length; i++) {     this.simulate('keyPress', extend({       which: characters.charCodeAt(i),       key: characters[i],       keyCode: characters.charCodeAt(i)     }, args));   } } 

7 Answers

Answers 1

You can use state to directly update the value of you textfield.

Let the value of text input in state be:

state = {    textInputValue: "" }; 

This is how you define your text input in React

<input type="text"   className="form-control"   name="my-text-input"   placeholder="text"   value={this.state.textInputValue}   onChange={this.onTextInputChange} /> 

Once you have defined your text input, you can update the value of your text input by just changing your state say this.setState({textInputValue: 'MyText'}) from within your react component. After that you can normally update the value of the text field using

onTextInputChange(event) {     let newText = event.target.value;     return this.setState({textInputValue: newText}); } 

I don't know what kind of scenario you are facing. Since React creates and maintains it's own virtual DOM, you can't manipulate the DOM elements with Jquery or Javascript from outside React. However if you need to get data from outside, use componentWillMount() in your React component to write code that gets data from your required data source and set it to the state of your TextInput

componentWillMount() {     // Code to get your data into variable 'defaultTextValue'     this.setState({textInputValue: defaultTextValue}); } 

Answers 2

As showcased in the react test utils docs in the simulate section, you can see what they're basically doing is changing the DOM node value and then triggering an input event.

What you could do is something like the following, calling it with your input DOM element and new value.

const changeValue = (element, value) => {   const event = new Event('input', { bubbles: true })   element.value = value   element.dispatchEvent(event) } 

Depends on how you defined your components though, if for example you're expecting an enter keypress, you'll have to dispatch the matching event.

Answers 3

According to this answer, you can get react instance from dom.

Assume the obj is a dom element.

function findReact(dom) {// from http://stackoverflow.com/a/39165137/4831179     for (var key in dom) {         if (key.startsWith("__reactInternalInstance$")) {             var compInternals = dom[key]._currentElement;             var compWrapper = compInternals._owner;             var comp = compWrapper._instance;             return comp;         }     }     return null; };  var instance = findReact(obj);  console.log(instance.state);//try to modify the form and check what's here  instance.setState({ //the state name from the previous step });  instance.submit();//something like this 

Answers 4

This will depend on the browser, but for text inputs the onChange call is listening to input events

element.value = 'new value'; var event = new Event('input', { bubbles: true }); element.dispatchEvent(event); 

Answers 5

Try to reassign the entire html content like

 $("html").on("DOMNodeInserted DOMNodeRemoved change", "body", function(){      $("body").html($("body").html());   });   // or call a simple function with $("body").html($("body").html()); 

I did that to reassign html and apply events again on svg tags in jquery after raw code injection ... maybe that ll work for this case too..

Try .on() method on the events either.

Answers 6

You can achieve this by using ReactDOM(https://facebook.github.io/react/docs/react-dom.html) and Jquery, is not very common to manipulate like this but it works:

var ctx = this;  //Save the context of your class to the variable ctx, since inside $/Jquery the this is a reference to $/Jquery itself. $(ReactDOM.findDOMNode(ctx.refs.myInput)).val('abc'); 

And your input must have a ref property to React find it:

<input type="text"   className="form-control"   ref="myInput"   placeholder="text" /> 

Answers 7

I've made a codepen with a working example of what I believe Dani Akash was trying to say. It is important to know that in React, setState() causes the component to rerender, hence in my example passing the new state as a prop to the child component.

https://codepen.io/tskjetne/pen/mmOvmb?editors=1010

  1. First I render the Parent component I created. The parent component contains a button and another React component I created InputWithButton
  2. The Parent constructor gets called first, setting the Parent components state to the object {value: "initial value"}
  3. The setValueInParent is a click handler I bind to the button in the Parent component. It sets the Parent components state which causes a rerender.
  4. The Parent component passes its state.value as a prop to the InputWithButton component.
  5. The InputWithButton component is very similar to the parent. Although, in the constructor it sets the state value to be the value prop passed in from the parent.
  6. Other than that the InputWithButton component works more or less the same way as the Parent component.

This enables you to change the input value by typing in the input field, clicking a button in the same component as the input field, and passing in a new value as a prop from a parent.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment