Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
195 views
Welcome To Ask or Share your Answers For Others

1 Answer

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...