Reputation: 81
I know this question has been asked before, but I've tried all of solutions I could find, and after wasting days on this, I'm literally about cry. What am I doing wrong?
The input field remains readonly
and onChange
won't fire despite my varied and increasingly desperate attempts to coax it into behaving like the most basic of text input fields.
here's my code:
import React, { Component, PropTypes } from 'react';
export default class Contact extends Component {
constructor(props) {
super(props);
this.state = { name: '' };
}
handleChange(e) {
this.setState ({ name: e.target.value });
}
render() {
return (
<div>
<form>
<input
type = "text"
value = { this.state.name }
onChange = { this.handleChange.bind(this) }
/>
</form>
</div>
);
}
}
EDIT: I just realized that it does work as expected as long as I add <Contact />
to a component that doesn't invoke componentDidMount()
. It would be super helpful if someone could give a breakdown of why that would make input fields readonly, i.e. does invoking componentDidMount()
somehow interfere with onChange
or setState
?
EDIT 2: componentDidMount()
only appeared to be the issue because the components where I invoked it were the ones that contained transitions/animations which I'd attempted to layer using z-index. It turns out that a negative z-index on a parent div can disable an input field by preventing you from being able to click into the text field, even if the input appears completely unobscured.
Upvotes: 4
Views: 9098
Reputation: 81
The z-index
of parent divs can make input fields appear readonly
by making it impossible for you to click into the field. This can happen even if the field appears completely unobscured. http://jsfiddle.net/t8542vcy/2/
In my code, a very distant parent div had a negative z-index, causing the input to silent fail. It functioned normally once I adjusted the z-index.
http://jsfiddle.net/t8542vcy/5/
I had no idea that z-index
could cause this and wasted SO much time writing and rewriting my code because I incorrectly thought it was a React issue. I shed literal tears and nearly lost the last shreds of my sanity. I can only hope that this helps someone tormented by a similar demon.
Check your z-index
, folks, check your z-index
.
Upvotes: 4
Reputation: 1593
To, fixed this you need to replace value
as defaultValue
so that you can change the value
property of input field
import React, { Component, PropTypes } from 'react';
export default class Contact extends Component {
constructor(props) {
super(props);
this.state = { name: '' };
}
handleChange(e) {
console.log(e.target.value); // make sure you are receiving the the value
this.setState ({ name: e.target.value });
}
render() {
return (
<div>
<form>
<input
type = "text"
defaultValue = { this.state.name } // here write defaultValue instead of value
onChange = { this.handleChange.bind(this) }
/>
</form>
</div>
);
}
}
Upvotes: 10