Home > database >  conditionally disable an option using react select not work when change option props passed to the S
conditionally disable an option using react select not work when change option props passed to the S

Time:02-23

I'm trying to conditionally make an option of a select disabled, for example, if two items are selected, the the third option is diabled, if one or three items are selected, the third option is enabled. However the Select option does not change when selected number of items change even it's passed as props of the option. When I console.log, I do see the option object disabled value changed when I change selected items numbers. May I know why the Select does not re render? Thanks!

class parentComponent extends PureComponent{
constructor(props) {
    super(props)
  this.state = {
    options:[]
  }
}
render() {
 const {
  countOfItems
 } = this.props
 
 let options = [...somefunction()];
 if (somecondition1) {
  options.options.filter(...)
 }
 if (somecondition2) {
  options.options.filter(...)
 }
 
 this.setState({options})
 ......
 if (countOfItems === 2) {
 options[3].disabled = true
 } else {
 options[3].disabled = false
 }
console.log(options[3])
......
return (
 <Select
  options ={options}
  isOptionDisabled = {(option) => option.disabled}
  ......


)
}
}

CodePudding user response:

React component render their UI/DOM after DOM diffing which causes the component to make a new reference of return statement and render updated changes to UI. which is triggered by useSTATE hook. If you are not updating state. No dom diffing occur. So you'll have the old reference of Dom.

You can do it this way

class Options {

this.state={options:[]}


componentDidUpdate(prevProps) {
  // Typical usage (don't forget to compare props):
  if (this.props.countOfItems !== prevProps.countOfItems) {
let tempOptions = [...this.state.options]
if (this.props.countOfItems === 2) {
 tempOptions[3].disabled = true
 } else {
 tempOptions[3].disabled = false
 }
this.setState({options:tempOptions})
  }
}





render() {
   
    ......
    return (
     <Select
      options ={this.state.options}
      isOptionDisabled = {(option) => option.disabled}
      ......
    
    
    )
    }
  • Related