React-why event target value is undefined

Viewed 1176

I am working on a shared component, which is an input textarea

The component is:

class TextBox extends React.Component {
  constructor(props) {
    ...
    const value = this.props.value;
    this.state = {
      value: value
    }
  }
  
  handleChange(e, v) {
   console.log("event: ", e);
   this.setState({value: e.target.value}, () => {this.props.handleChange(e, v)});
  }

  render() {
    const {
      name
    } = this.props;

    const {
       value
    } = this.state;

    return (
      <div>
         <h2>{name}</h2>
         <textarea
           value={value}
           onChange={this.handleChange}
         />
      </div>
    );
  }
}

Using this component:

   const [comment, setComment] = useState('');
   const handleChange = useCallback((e, v) => {
      setComment(v);
   }, [comment]);

    ....
    <TextBox 
      name="comment"
      value={comment}
      handleChange={handleChange}
    />

The console log shows event.target.value is undefined I have no idea why, can someone help? Thanks in advance

===update=== Thank you all! The problem is fixed

2 Answers

This should be target and value from the first parameter:

  handleChange = (e) => {
   console.log("event: ", e);
   console.log("value: ", e.target.value);
    this.setState({value: e.target.value}, () => {this.props.handleChange(e, v)});
  }

Inside the above function:

  • e - Window.Event
  • e.target - <textarea> element in JS.
  • e.target.name will be the name attribute.
  • e.target.value will be the value attribute.

Also I'll suggest you to use Arrow Functions, else you might need to bind the function to this on the constructor, which is not being followed now-a-days.

You have to bind the handleChange function in constructor like below:

this.handleChange=this.handleChange.bind(this);

You can also use arrow function like this way:

handleChange=(e)=>{//...content here}

Also, there is no such parameter as v. The only parameter should be e.

Related