Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Why is input field still readonly (i.e. not editable) even though I've added onChange?

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 onChangeor 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.

like image 456
caitbun Avatar asked Dec 15 '22 04:12

caitbun


1 Answers

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>
    );
  }
}
like image 147
Md.Estiak Ahmmed Avatar answered Jan 11 '23 09:01

Md.Estiak Ahmmed