scorezel789
scorezel789

Reputation: 163

Why can't I change the input field value in React?

The current problem I am having is that after retrieving and setting the value, I am not able to edit the value in the input field after retrieving it. The value seems to be static and uneditable in the input field.

I want have to have flexibility to change the input field value even after retrieving the value.

Below is just a snippet of my code as to post the entire code is very large. I believe the problem lies inside the render() where i set the value={something} and handleInputChange.

Can someone tell me what is wrong with my code?

constructor(props) {
    super(props);

    this.state = {
        seedURL: '',
        response: null,
        error: null, 
        loading: false
    };
    this.handleInputChange = this.handleInputChange.bind(this);
}

handleInputChange = (e) => {
    e.preventDefault();

    let name = e.target.name;
    let value = e.target.value;

    this.setState({
        [name]: value
    });
};



render() {
    const name = this.state.response ? this.state.response.data.name : "";
    const image = this.state.response ? this.state.response.data.image : "";

    return(
        <form>
            <input type="text" placeholder="Business Name" name="name" onChange={this.handleInputChange} value={name} />
            <input type="text" placeholder="Image URL" name="image" onChange={this.handleInputChange} value={image} />
        </form>
    );
}

Upvotes: 0

Views: 151

Answers (2)

raven
raven

Reputation: 2431

name and image are not defined in the state of your component.

 this.state = {
        seedURL: '',
        response: null,
        error: null, 
        loading: false
    };

You could add them, e.g

 this.state = {
        seedURL: '',
        response: null,
        error: null, 
        loading: false,
        image: '',
        name: ''
    };

But you will have to bind to this properties in the inputs like this:

<input type="text" placeholder="Business Name" name="name" onChange={this.handleInputChange} value={this.state.name} />

Alternatively, if you want to change the value of your response property of the state then you could use the spread operator to set the state of this object.

this.setState({
  ...this.state,
  response: {
    ...this.state.response,
    data: {
      ...this.state.response.data,
      [name]: e.target.value
    }
  }
})

Upvotes: 1

rzwnahmd
rzwnahmd

Reputation: 1082

That is because you're setting the value of input but that value is not changing when you type, to change those values you'll have to modify your setState() call to this:

this.setState({
  response: {
    ...this.state.response,
    data: {
      ...this.state.response.data,
      [name]: [value]
    }
  }
})

Hope this helps :)

Upvotes: 0

Related Questions