jeudi 23 mars 2017

Checkbox not changing check attribute after state was changed

Here is a some parts of code I am using:

class FileItem extends Component {

  constructor(props) {
    super(props);

    // Initial state
    this.state = {
      hover: false,
      checked: false
    };

    this.pickFile = this.pickFile.bind(this);  

  }

  pickFile(e){
   e.stopPropagation();
   this.state.checked ? this.props.removeSelectedPaths(this.props.path) : this.props.addSelectedPaths(this.props.path);
  }

  //set the checked status for the checkboxes if file\folder are picked
  componentWillReceiveProps(nextProps){

   console.log('Paths updated',nextProps.selectedPaths);

   const selected = nextProps.selectedPaths.indexOf(this.props.path) != -1;

   this.setState({checked: selected });

 } 

 render(){

  return(          
      <div className='select-mode'><input id='files-select' type='checkbox'  checked={this.state.checked} onClick={this.pickFile}/></div>
  )

 }

How this should work:

When you pick a file it should set the checked status of its checkbox. And when you use slect all files checkbox( it is not in code here) it pushes all paths to the redux state in the selectedPAths array and all files should have checked checkboxes as they are selected.

The problem:

The problem is when I use Select All files functionality the checkbox for individual file not setting it checked status to true. While picking file by file is working fine and checkbox changes to checked(but same logic is used to see if it should be checked).

Weird facts:

  1. When I do console.log(this.state.checked) in render it shows me that state is true. So it should change checkbox to checked but not.
  2. I have a similar logic for the Select All files checkbox ( it uses componentWillReceiveProps method to check if all files was selected and change the checked status) and it is working just fine.
  3. You can reveal that the checkbox checked after you picked all files just hovering it over(which triggers on mouse enter event and changes the state which leads to re rendering). I have a feeling like a render is getting lost after state changed but the weird fact 1 tells opposite thing as we have true in state but not checked checkbox in UI.



Aucun commentaire:

Enregistrer un commentaire