Gibrahh
Gibrahh

Reputation: 183

Empty string check on Input element value

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;

Upvotes: 1

Views: 252

Answers (1)

Mosh Feu
Mosh Feu

Reputation: 29239

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

Upvotes: 2

Related Questions