Saturday, May 25, 2024
 Popular · Latest · Hot · Upcoming
195
rated 0 times [  200] [ 5]  / answers: 1 / hits: 25306  / 8 Years ago, wed, november 30, 2016, 12:00:00

I'm tasked with crawling website built with React. I'm trying to fill in input fields and submitting the form using javascript injects to the page (either selenium or webview in mobile). This works like a charm on every other site + technology but React seems to be a real pain.



so here is a sample code



var email = document.getElementById( 'email' );
email.value = '[email protected]';


I the value changes on the DOM input element, but the React does not trigger the change event.



I've been trying plethora of different ways to get the React to update the state.



var event = new Event('change', { bubbles: true });
email.dispatchEvent( event );


no avail



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


not working



email.onChange( event );


not working



I cannot believe interacting with React has been made so difficult. I would greatly appreciate any help.



Thank you


More From » reactjs

 Answers
14

React is listening for the input event of text fields.



You can change the value and manually trigger an input event, and react's onChange handler will trigger:





class Form extends React.Component {
constructor(props) {
super(props)
this.state = {value: ''}
}

handleChange(e) {
this.setState({value: e.target.value})
console.log('State updated to ', e.target.value);
}

render() {
return (
<div>
<input
id='textfield'
value={this.state.value}
onChange={this.handleChange.bind(this)}
/>
<p>{this.state.value}</p>
</div>
)
}
}

ReactDOM.render(
<Form />,
document.getElementById('app')
)

document.getElementById('textfield').value = 'foo'
const event = new Event('input', { bubbles: true })
document.getElementById('textfield').dispatchEvent(event)

<script src=https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js></script>

<div id='app'></div>




[#59859] Tuesday, November 29, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarrettw

Total Points: 300
Total Questions: 98
Total Answers: 103

Location: Saudi Arabia
Member since Mon, Sep 5, 2022
2 Years ago
;