简体   繁体   中英

Cannot read properties of undefined (reading 'length') using reactjs

When manually entering a name, the user can see a character counter letting the user know how many characters the user has typed so far, and when the user is approaching or reaches the limit of 20 characters. and if it reach the limit the textfield will shakey

  const CHARACTER_LIMIT = 20;
  const [values, setValues] = React.useState([]);

  const handleChange = (name) => (event) => {
    setValues({ ...values, [name]: event.target.value });
  };

  <h1>Text Field with character limit</h1>
  <TextField
    label="Limit"
    inputProps={{
      maxlength: CHARACTER_LIMIT
    }}
    value={values.name}
    helperText={`{${values.name.length} === undefine ? 0 : ${values.name.length}}/${CHARACTER_LIMIT}`}
    onChange={handleChange("name")}
    margin="normal"
    variant="outlined"
  />

There are some error in your code, when you define the initial value of the values state It's equal to an empty array but when changes are performed on the TextField the handleChange method update the value of that state as if it was an Object. which will cause the values state to not have length property

You can use two different states to manage value entered in the text field and the length

Here is sample which use the value and length of the value of the input field to set some custom behavior on the output

 class App extends React.Component { render() { return <div> <TextField /> </div> } } class TextField extends React.Component { constructor(props) { super(props); this.state = { value: "", length: 0, }; } handleChange = (event) => { this.setState({ value: event.target.value, length: event.target.value.length }) } render() { return <div> <h2>{this.props.label}</h2> <input type="text" value={this.state.value} onChange={this.handleChange} className={this.state.length > 20? "red": null}/> <div> <strong>Length</strong>: {this.state.length} </div> </div> } } ReactDOM.render(<App />, document.querySelector("#root"));
 .red { color: red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM