Search code examples
javascriptfunctionreactjsonblur

How to fire onBlur event in React?


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.


Solution

  • 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: () => {},
    };