ReactJS: Cannot get the length of a string in component state

react get state value
react state array length
react get input value length
react array length undefined
cannot read property 'length' of undefined react
conditional rendering react
string validation in react js
react render conditionally from props

I have a little problem. In my function isLoginOk() it never enters into the if. It enters every time in the else even if my string is longer than 1 char.

When I console.log before the if I can see that my string is longer than 1 yet it doesn't go into the if!

Why is that? (I have verified that the string in my component state is correctly updated by handleChange())

export default class InputLogin extends React.Component {
        constructor(props) {
            super(props);
        this.state = {
            login: "",
        }
    };

    handleChange = (e) => {
        this.setState({
            [e.target.name]: [e.target.value]
        });
    }

    isLoginOk() {
        if (this.state.login.length > 1) {
            return (<div>OK</div>);
        } else {
            return (<div>ERROR</div>);
        }
    }

    render() {
        return (
            <div>
                <input type="text" name="login" value={this.state.login} onChange={this.handleChange} /> {this.isLoginOk()}
            </div>
        );
    }
}

It looks like an inconsitency with the way you're setting the component state in handleChange() versus the way isLoginOk() expects the state to be defined.

In the handleChange() function, the "square bracket" syntax [e.target.value] means that you're setting the state value for key [e.target.name] as an array:

 this.setState({
        // Brackets around [e.target.value] creates array value
        [e.target.name]: [e.target.value] 
 });

The isLoginOk() function however, expects the value to be a string rather than an array:

isLoginOk() {

    // You're accessing the string directly and not as an array item
    if (this.state.login.length > 1) {
        return (<div>OK</div>);
    } else {
        return (<div>ERROR</div>);
    }
}

Consider revising your handleChange() function like so to ensure that the state is updated in a way that is compatible with isLoginOK():

handleChange = (e) => {
    this.setState({
        [e.target.name]: e.target.value // Remove the [ and ] around value
    });
}

ReactJS: Cannot get the length of a string in component state, I have a little problem. In my function isLoginOk() it never enters into the if. It enters every time in the else even if my string is longer than 1 char. When I  There are even ways to manipulate a parent component's state from a child component. By the end of this post, you'll know how to do both. State Management in a React js Component. Before we can get into the details about creating a state within our component, it's important to note that state can only be created in a class component. The reason

There is a bug in your code, in your handleChange value.

[e.target.name]: [e.target.value]

You're setting the value of this.state.login to ['some input']. Your validation always fails because you can't get the length of the string inside the array using this.state.login.length. Your validation will return either 0 or 1 based on the array length, certainly not what you intended.

To fix this, remove the brackets around [e.target.value].

class InputLogin extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      login: ""
    }
  }
  
  handleChange = (e) => {
    this.setState({
      [e.target.name]: e.target.value
    });
  }
  
  render() {
    const { login } = this.state;
    const loginResult = login.length > 1 ? "OK" : "ERROR";
    
    return (
      <div>
        <input type="text" name="login" value={login} onChange={this.handleChange} />
        {loginResult}
      </div>
    )
  }
}

ReactDOM.render(<InputLogin />, document.querySelector("#app"))
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
  color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>


<div id="app"></div>

ReactJs Get Array Length, What kind of error types are not caught by error boundaries? While both hold information that influences the output of render, they are different in one important way: props get passed to the component (similar to function parameters) whereas state is managed within the component (similar to variables declared within a function).

Remove the brackets around e.target.value

Also simplify the render and get rid of the isLoginOk function. Seems unnecessary.

<input type="text" name="login" value={this.state.login} onChange={this.handleChange} /> 
<div>{ this.state.login.length > 1 ? 'OK' : 'ERROR' }</div>

Understanding Error Boundaries in React, for: Event handlers. setTimeout or requestAnimationFrame callbacks. Server side rendering. Warning: Cannot update a component from inside the function body of a different component. This warning will help you find application bugs caused by unintentional state changes. In the rare case that you intentionally want to change the state of another component as a result of rendering, you can wrap the setState call into useEffect .

What is the smallest building block of ReactJS, Can't perform a React state update on an unmounted component This is a no op? setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.

React state update on an unmounted component, , but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. To implement this, we need to add “state” to the Clock component. State is similar to props, but it is private and fully controlled by the component. Converting a Function to a Class . You can convert a function component like Clock to a class in five steps: Create an ES6 class, with the same name, that extends React.Component.

Array length cannot be read · Issue #10383 · facebook/react · GitHub, Uncaught TypeError: Cannot read property 'length' of undefined. but anyway I think that it doesn't have anything to do with React. I think that you want to access variable from state of your component and you have to bind 'this' to your event handler function in constructor of your class based component Typically, new React apps have a single App component at the very top. However, if you integrate React into an existing app, you might start bottom-up with a small component like Button and gradually work your way to the top of the view hierarchy. Extracting Components . Don’t be afraid to split components into smaller components.

Comments
  • React is a framework for JavaScript, it doesn't change how JavaScript works. So if this.state.login.length > 1 is never true then you are not setting the value of this.state.login correctly. Did you verify that e.target.name is what you expect it to be?
  • Hello,I did it's fine
  • Good catch! It would be useful to explain what the [...] around e.target.value mean and why that causes the condition to always fail.
  • @FelixKling thanks - I've just updated the answer with a some extra detail and documentation
  • Hello, that was the problem. However my login variable was correctly updated. It's a strange behaviour but you found the problem. Thanks
  • I just did it. I needed 2 min to do so because of my last post ;) thanks and thx for the explanation