How to fire onBlur event in React?

10,070

Thanks to the comments, I was able to figure it out. I had to add an onBlur prop to Input like so:

export default class Input extends React.Component {
  constructor() {
    super();
    this.handleBlur = this.handleBlur.bind(this);
  }

  handleBlur() {
    const { onBlur } = this.props;
    onBlur();
  }

  render() {
    return <input onBlur={this.handleBlur} />
  }
}

Input.propTypes = {
  onBlur: PropTypes.func,
};

Input.defaultProps = {
  onBlur: () => {},
};
Share:
10,070

Related videos on Youtube

Ralph David Abernathy
Author by

Ralph David Abernathy

Updated on May 30, 2022

Comments

  • Ralph David Abernathy
    Ralph David Abernathy about 2 years

    I have an input field value that I want to format onBlur, here is what my code looks like:

    Component:

      <Input
        onBlur={this.formatEndpoint}
      />
    

    Function:

      formatEndpoint() {
        let endpoint = this.state.inputEndpoint;
    
        endpoint = endpoint.replace(/\s/g, '').replace(/\/+$/, '');
    
        if (endpoint.slice(-1) === '/') {
          endpoint = endpoint.substring(0, endpoint.length - 1);
        }
    
        console.log('anything');
      }
    

    Why doesn't even the console.log() work onBlur? Thanks.

    • Panther
      Panther over 6 years
      Looks like its a custom input. You should check if the component supports onBlur.
    • mikkelrd
      mikkelrd over 6 years
      Yes, what does the definition of Input look like? Did you write it?
    • Ralph David Abernathy
      Ralph David Abernathy over 6 years
      These comments helped, I just had to add an onBlur prop to Input.