Javascript – React.js setting value of input

htmljavascriptjqueryreactjs

I am a beginner with react.js and it's amazing but I am facing a real problem: I need to set the value of an input using plain and pure javascript but form some reason react.js is not working as expected. Take this example: open this URL http://autoescolalatorreta.wix.com/latorreta#!contact/c24vq

You will see there is an "Email" input field which id is "CntctFrm2emailField". I try to change the value of it using javascript with this code:

document.getElementById("CntctFrm2emailField").value = "testing@gmail.com";

But for some reason React.js is not updating this value on its core cause if you try to send the form (Clicking the SEND button) you will see that it will display an error message saying that email is not filled right. BUT once I click inside the email field and type any letter and click the SEND button it works fine, I mean, React.js sees the new value.

So how can I change an input value and have React.js to update that value too?

Best Solution

For React 16 above solutions are not working. Check this issue from GitHub.

function setNativeValue(element, value) {
    let lastValue = element.value;
    element.value = value;
    let event = new Event("input", { target: element, bubbles: true });
    // React 15
    event.simulated = true;
    // React 16
    let tracker = element._valueTracker;
    if (tracker) {
        tracker.setValue(lastValue);
    }
    element.dispatchEvent(event);
}

var input = document.getElementById("ID OF ELEMENT");
setNativeValue(input, "VALUE YOU WANT TO SET");