A. Sinha
A. Sinha

Reputation: 2716

How to remove spaces onPaste in reactjs

How can I remove space from a string when pasted in a textfield in Reactjs using onPaste event so that the final string that appears inside the text field has no spaces in between.

My HTML code is as follows:

<input placeholder="Enter your First Name" onPaste={(event) => this.onFirstNamePaste(event)}/>  

event handler:

onFirstNamePaste(event){
    var text = event.clipboardData.getData('Text')
    this.value = text.replace(/\s/g,'');
 }

Upvotes: 1

Views: 5538

Answers (2)

pratZ
pratZ

Reputation: 3346

Use the ref attribute for the input element,

<input 
    ref={(nameInput) => { this.nameInput = nameInput; }}
    placeholder="Enter your First Name"
    onPaste={(event) => this.onFirstNamePaste(event)}
/>

And then inside the function,

onFirstNamePaste(event){
    const text = event.clipboardData.getData('Text')
    this.nameInput.value = text.split(' ').join('');
}

You can also use the component state to track the changes in the input and update the state to reflect the changes.

<input 
    value={this.state.nameValue}
    onChange={(e) => this.setState({ nameValue: e.target.value }) }
    placeholder="Enter your First Name"
    onPaste={(event) => this.onFirstNamePaste(event)}
/>

In the paste function,

onFirstNamePaste(event){
    const text = event.clipboardData.getData('Text')
    const value = text.split(' ').join('');
    this.setState({ nameValue: value });
}

Upvotes: 0

Alex Borodin
Alex Borodin

Reputation: 2034

Try this:

 onFirstNamePaste(event){
    var text = event.clipboardData.getData('Text')
    this.value = text.split(' ').join('');
 }

Upvotes: 1

Related Questions