How to disable a button from react component inherited by a child react component?

Viewed 712

I have a child react component that extends a parent react component.

The child component is a form and it inherits a button that saves the form from parent.

In some situations, if validation on the form fails in child component, the save button from parent component should be disabled.

How do I disable that parent button from the child component?

this is the parent's render function looks like:

render() {
return (
  <Modal open={this.props.open} onClose={this.props.onClose.bind(this.props.parent)}>
      <Modal.Content>
        <Modal.Description>
          {this.getDescription()}
        </Modal.Description>
      </Modal.Content>
      <Modal.Actions>
        <Button className="buttontype1" onClick={this.props.onSave.bind(this.props.parent)}>{this.getLocalValue('savebutton', 'Save')}</Button>
        <Button className="buttontype2" onClick={this.props.onClose.bind(this.props.parent)}>{this.getLocalValue('cancelbutton', 'Cancel')}</Button>
      </Modal.Actions>
    </Modal>
);

}

or if it's possible to overwrite the parent's onSave?

thanks.

1 Answers

you may set up a state in the parent component and pass this condition to the child button, like this:

parent:

import React, { useState } from 'react';
import Child from '../path-to/Child';

const Parent = () => {
   const [condition, setCondition] = useState(false);

   return <Child condition={condition} />;
}

**child: **

import React, { useState } from 'react';

const Child = ({condition, setParent}) => {
    const handleValidate = () => {
        let condition = true;   
        setParent(condition);    
    }

    return <button disabled={condition} setParent={setCondition} />;
}

Related