How to validate input each time the component is updated in react

I have a container which has a validate method to enable/disable search button based on user input.
When the input is empty the search button is disabled.
The container has two forms for providing input. When we switch the tabs the user input gets cleared as well as the results but the search button is enabled even if the input is empty.
Any suggestions on how to resolve it?

Without seeing the source code is a wild guess how to precisely help you, but:

  • you can use componentWillReceiveProps(newProps) in the lifecycle method to catch some props being updated and react from that.

A mockup example would be:

  // get the input being cleared
  if( newProps.inputValue === undefined) {
    // set the button as disabled
    this.setState({ buttonDisabled: true});

What however usually do in my Component when I have a case like this is simply pass a disabled prop to a Button component that will render the disabled button:

// all you component above
return (
 <Button disabled={!this.state.inputValue ? true : false} />
// and then in my Button.js
const Button = ({disabled}) => {
  const classToAdd = disabled ? 'button-diasbled' : 'default-button';

  return (
     <button className={classToAdd}>
         my button text

Hope it helps setting you on the right track :smile:

1 Like