Mijeong Won
Mijeong Won

Reputation: 351

React/JavaScript Prevent onKeyDown typing (other langs)

The reason why I use onKeyDown is the lang for typing is Korean.

I have several inputs and when users type over than 20 bytes, I want to stop them to keep typing.

//this calculates bytes
const getByteLength = (s,b,i,c) => {
    for(b=i=0;c=s.charCodeAt(i++);b+=c>>11?3:c>>7?2:1);
    return b;
}

.

handleLength = (e) => {
    let currentBytes = getByteLength(e.currentTarget.value);
    // checked : it calculates bytes successfully.
    if (currentBytes > 20){
        // checked : This is only working for English. When I type over than 20 bytes, this removes the lastest letter. but I still can type Korean.
        e.currentTarget.value = 
        e.currentTarget.value.substring(0,e.currentTarget.value.length - 1);
    }
}

<input onKeyDown={this.handleLength}>

Upvotes: 1

Views: 108

Answers (1)

Masious
Masious

Reputation: 430

You should save the value of your input in a state variable:

class Foo extends Component { state = { value: '' };

handleLength = (e) => {
    let currentBytes = getByteLength(e.currentTarget.value);
    // checked : it calculates bytes successfully.
    let value = e.currentTarget.value;
    if (currentBytes > 20){
        value = e.currentTarget.value
            .substring(0,e.currentTarget.value.length - 1);
    }
    this.setState({ value });

}

And then use the value in the state, in your input:

<input value={this.state.value} onKeyDown={this.handleLength} />

Upvotes: 2

Related Questions