Reputation: 23
start to learn React.js recently and encounter the following problem: enter image description here
I want to get the div
element using getElementById
but it doesn't work and the console alerts can not read property 'props' of null
. So how can I get the div
element? it has troubled me for several hours.
Thanks.
Upvotes: 1
Views: 5558
Reputation: 832
The whole idea with React is that you don't access the DOM, but work with a virtual DOM.
To achieve what you are trying to accomplish (which is a little unclear since the code is incomplete), you'll want to use a stateful component that stores user input on this.state
. Check out this page on React forms.
You'll want to do something like this, where you are tracking user input by storing it on the component:
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
Upvotes: 2