I'm using the npm package react-sortablejs
. In my component I want to set the disabled
option dynamically. Right now my component looks like this:
class Example extends Component {
constructor(props) {
super(props)
this.state = { }
}
render() {
const { disabled } = this.props // <-- Boolean value as property
return (
<List>
<Sortable
options={{
handle : '.sortable-handle',
draggable: '.sortable-item',
disabled : disabled // <-- Use the bool value
}}
>
<Items>
</Sortable>
</List>
)
}
}
The disabled
value is stored in the DB. If that value changes, the sortable should be disabled/enabled. But in this way it doesn't work.
The package is based on RubaXa/Sortable
. There I can set the disabled option like this:
var sortable = Sortable.create(list);
document.getElementById("switcher").onclick = function () {
var state = sortable.option("disabled"); // get
sortable.option("disabled", !state); // set
};
But how do I do that in a dynamic way in a react component?
Update
In the way I did it, the disabled
option is just set initially on rendering the component. If the value changes after rendering, the option is not changed, so if the value changes from true
to false
, the disabled-option still keeps true.
i think that you have to bind the whole "option" variable. judging from the lack of maintainer in react-sortablejs, it does not really bind to nested value yet.
try to put the options on state.
constructor(props) {
super(props);
this.state = {
option : {
handle : '.sortable-handle',
draggable: '.sortable-item',
disabled : true
}
}
}
bind the state's option
<Sortable options={this.state.option}>
<Items>
</Sortable>
And on ComponentDidUpdate() ,do this:
componentDidUpdate(prevProps, prevState) {
if(prevProps.disabled !== this.props.disabled){
this.setState({option : Object.assign({}, this.state.option, {disabled: this.props.disabled})})
}
}
my guts telling me that the component does not recognized the disabled update due to nested props. the whole option must be updated, so that it recognize the change.
OR>
you can pass the options as props instead. and do the update on parent's component, each time the disabled change.