1

Why isn't my empty string check working as expected on an HTMLInputElement value property after trim? Problem code in storeOnEnter function. The goal is to only set new state when the input is empty.

import React, { Component } from 'react';

class ItemEditor extends Component {
    state = {
        showInput: true,
        itemDescription: ''
    }

    storeOnEnter = (e: React.KeyboardEvent<HTMLInputElement>) => {
        if (e.key !== 'Enter') return;

        const input = e.target as HTMLInputElement;
        if (!input.value.trim) return;

        this.setState({itemDescription: input.value, showInput: false})
    }

    switchToInput = (e: React.MouseEvent) => {
        this.setState({showInput: true});
    }

    render() {
        let input = <input type="text" onKeyPress={this.storeOnEnter} defaultValue={this.state.itemDescription}/>
        let label = <label style={{userSelect: 'none'}} onDoubleClick={(e) => this.switchToInput(e)}>{this.state.itemDescription}</label>

        return this.state.showInput ? input : label;
    }
}

export default ItemEditor;

1 Answer 1

2

trim is a function. That's why !input.value.trim is always truthy. Use !input.value.trim() instead.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

Sign up to request clarification or add additional context in comments.

2 Comments

Doh. Might have to stick to Kotlin after hours, stupid lack of sleep mistake wow... thank you
It happened to the best :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.