Search code examples
javascriptreactjsonblur

onBlur event runs automatically when loading application ReactJS


I'm working with ReactJS and I need to execute a validation to an input text so I using onBlur but it runs automatically when loading the application.

My code is very simple to the example:

onBlur ={ alert() }

How can I prevent onBlur from running automatically?

Thanks!


Solution

  • yo just need to give the function name there and on blur react will execute this function. so you need to write this:-

    onBlur ={ alert }
    

    edit based on the comment, The code which you have posted should have the same behavior, you can put a console.log in the error function, I am sure it will get called, providing you are not getting any error.

    now I guess you want to pass some data in the callback and that's why going with this approach, to achieve the same you can use

    onBlur ={ ()=>{this.error('lastName');} }