I've been building React components for my latest app. I know I can reuse components which has helped keep my code DRY.
I wanted to know if I could reuse functions. I know there has to be a way.
Right now I have three components using a password validation function.
passwordValidation() {
const length = this.state.password.length;
if (length > 7) return 'success';
else if (length > 4) return 'warning';
else if (length > 0) return 'error';
}
I created a helper file - helpers.jsx and added:
export function passwordValidation() {
const length = this.state.password.length;
if (length > 7) return 'success';
else if (length > 4) return 'warning';
else if (length > 0) return 'error';
}
I then imported it into my component
import { passwordValidation } from '../helpers.jsx'
I keep getting the error "passwordValidation is not a function" when I try binding "this" in my constructor.
If I invoke it in the input tag, I am getting "cannot read property state of undefined."
Just trying to see where I am going wrong. Everything works if I define it in my class and add this.passwordValidation = this.passwordValidation.bind(this).
I'll go back to what I was doing if this isn't best practice, but I'm under the assumption that I should be able to import functions to make life easier and my code cleaner!