bgardne7
bgardne7

Reputation: 93

React - e.target.value returns undefined

trying to return the string "blue" (so I can use setState to change the color) within:

<div className="colorBox blue" value="blue" onClick={changeColor}></div>

using this function:

const changeColor = (e) => {
  e.preventDefault()
  this.setState({ color: e.target.value })
}

but I only receive undefined when I log it to the console

Upvotes: 0

Views: 2265

Answers (2)

Abhishek
Abhishek

Reputation: 104

div element can't have value attribute, if you are trying to change color use input element of type color <input type="color" value="" /> .
Example:

<input type="color" value={//default color form your state} onChange={changeColor} 
const changeColor = (e) => {
    const color = e.target.value;
    this.setState({color});
}    

for more information about input color checkout MDN docs: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/color

Upvotes: 2

Riyaz Khan
Riyaz Khan

Reputation: 3288

The div tag doesn't contain the property value in the target object even if you add attribute.

If you want to get the value, you can use the button tag or input, but for your example, the button would be good.

Here is the example:

<button className="colorBox blue" value="blue" onClick={changeColor}></button>

Same function:

const changeColor = (e) => {
    e.preventDefault()
    this.setState({ color: e.target.value })
  }

Upvotes: 2

Related Questions