Don't directly manipulate any of the DOM that is rendered by React. When you change the disabled attribute, React is likely to overwrite your change. The good news is that direct DOM manipulation is totally unnecessary.
Use props and state to control the DOM.
In the following code, the disabled attribute of the button is controlled by the disabled property of the component's state. When the checkbox is toggled, the onChangeDisabled method is called, which sets the disabled property of the component's state (via setState) to the opposite of the checkbox's checked state. Importantly, the call to setState triggers a re-render of the component, which applies the latest value of this.state.disabled to everything that refers to it in render.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.onChangeDisabled = this.onChangeDisabled.bind(this);
this.onDeleteAll = this.onDeleteAll.bind(this);
this.state = {
disabled: props.initialDisabled || false
};
}
onChangeDisabled(e) {
this.setState({disabled: !e.target.checked});
}
onDeleteAll(e) {
this.props.onDeleteAll();
}
render() {
return (
<div>
<button
disabled={this.state.disabled}
onClick={this.onDeleteAll}
>
<Trans>DELETE_ALL</Trans>
</button>
<input
type="checkbox"
checked={!this.state.disabled}
onChange={this.onChangeDisabled}
/>
</div>
);
}
}
MyComponent.propTypes = {
initialDisabled: PropTypes.bool,
onDeleteAll: PropTypes.func
};
MyComponent.defaultProps = {
onDeleteAll: () => {}
};
Or if you're using the latest ES features:
class MyComponent extends React.Component {
static propTypes = {
initialDisabled: PropTypes.bool,
onDeleteAll: PropTypes.func
};
static defaultProps = {
onDeleteAll: () => {}
};
state = {
disabled: this.props.initialDisabled || false
};
onChangeDisabled = ({target: {checked}}) => {
this.setState({disabled: !checked});
};
onDeleteAll = () => {
this.props.onDeleteAll();
};
render() {
return (
<div>
<button
disabled={this.state.disabled}
onClick={this.props.onDeleteAll}
>
<Trans>DELETE_ALL</Trans>
</button>
<input
type="checkbox"
checked={!this.state.disabled}
onChange={this.onChangeDisabled}
/>
</div>
);
}
}
Alternatively, you can control disabled from the outside so that MyComponent becomes stateless:
const MyComponent = ({
disabled = false,
onChangeDisabled = () => {},
onDeleteAll = () => {}
}) => (
<div>
<button
disabled={disabled}
onClick={() => void onDeleteAll()}
>
<Trans>DELETE_ALL</Trans>
</button>
<input
type="checkbox"
checked={!disabled}
onChange={({target}) => void onChangeDisabled(!target.checked)}
/>
</div>
);
MyComponent.propTypes = {
initialDisabled: PropTypes.bool,
onDeleteAll: PropTypes.func
};