1

I have a component which get props a:[] b:[] values might be 1, 2, 3, 4

I have 8 checkboxes with name="a" and "b" with value="1" , "2","3" and "4" respectively if it was onClick or onChange I can get them by event.target.value and event.target.name

is it possible to set the defaultChecked with function? something like

<input name="a" type="checkbox" value="1" defaultChecked={this.checkIt.bind(this,name,value)} />

checkIt(this,name.value) {
if (this.props.name.indexOf(value)>=0)
{
   return true;
}
return false;
}
iMMuNiTy
  • 476
  • 7
  • 20

1 Answers1

1

Is it possible to set the defaultChecked with function?

Yes, it is possible, but you don't need to bind anything, simply call a function and return true or false on the basis of condition. Binding of function is not required because you want to call the function and assign the retuned value to defaultChecked.

Like this:

defaultChecked={this.checkIt(name,value)}

checkIt(name, value) {
    if (this.props.name.indexOf(value) >= 0)
        return true;
    return false;
}

For more details check this answer: Why is JavaScript bind() necessary?

Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
  • Just `return this.props.name.indexOf(value) >= 0;` – Igor Soloydenko Jan 02 '18 at 18:33
  • React responses with erro Line 60: Unexpected use of 'name' no-restricted-globals Line 60: 'value' is not defined no-undef – iMMuNiTy Jan 02 '18 at 18:35
  • @iMMuNiTy that issue is related variable names, just check all the variable should be defined, if you are creating elements inside map then name and value should be present, can you show full code? – Mayank Shukla Jan 02 '18 at 18:38