Eranga Kapukotuwa Eranga Kapukotuwa - 1 month ago 12
React JSX Question

React, How to detect a specific character is typed inside a form field

I have an "input field" component. I need to show an alert, if the "#" character is typed inside the input field. Is there any way, we can determine the character is typed.

export default class MyComponent extends Component {

constructor(props) {
super(props);
this.state = {};
}

handleKeyPress(e) {
// show an alert if "#" character is pressed
}

render() {
return (
<input onChange={this.handleKeyPress}>
)
}
}


Edit

I wanted to show the alert just after the user typed a "#" character. afterward he can continue typing any character without an alert prompting. If the user type another "#" inside the input field, the alert should be appeared again.

Any idea is appreciated.

Answer
export default class DayView extends Component {

  constructor(props) {
    super(props);
    this.state = {
      value: ''
    };

    // Bind `this`
    this.handleKeyPress = this.handleKeyPress.bind(this);
  }

  handleKeyPress(e) {
    // Get input value
    var value = e.target.value;
    // User has already typed a #
    var hasSymbol = !!value.substring(0, value.length - 1).match(/\#/);

    // Check if last character is a #
    if (value[value.length - 2] === '#') {
      alert('There is a # symbol');
    }

    // Check if this last character is a #
    // and the value already has one
    if (hasSymbol && value[value.length - 1] === '#') {
      alert('There is an other # symbol');
    }

    // Set state
    this.setState({ value });
  }

  render() {
    return (
      <input onChange={this.handleKeyPress} value={this.state.value}>
    )
  }
}