I am trying to make FlatList which reads data from const "values" and renders a list of checkboxes. For the checkbox I use Checkbox.Android from react-native-paper.
Const "values" contain following data:
const values = [
{
name: 'Checkbox 1',
[check, setCheck]: React.useState(false),
},
{
name: 'Checkbox 2',
[check, setCheck]: React.useState(false),
},
];
React Hook works when I use const [check, setCheck] = React.useState(false);
, but how to place it inside of "values"?
I am getting error:
Unexpected token, expected "]"
123 | {
124 | name: 'Checkbox 1',
> 125 | [check, setCheck]: React.useState(false),
| ^
126 | },
127 | {]
Sorry, I'm new with this and I couldn't find any complex examples like this case. Or is this not possible https://reactjs.org/docs/hooks-rules.html:
Don’t call Hooks inside loops, conditions, or nested functions
CodePudding user response:
thats not possible according to rule of hooks. but you can do it like this.
//your checkbox state
const [checkbox,setcheckbox] = useState([
{
name: 'Checkbox 1',
checked:false,
},
{
name: 'Checkbox 2',
checked:false,
},
]);
and then loop the data or use flatlist
<Flatlist
data={checkbox}
renderItem={({item,index})=>{
return (
<Pressable onPress={()=>{
let newcheckbox = checkbox;
newcheckbox[index].checked = !checkbox[index].checked;
setcheckbox(newcheckbox)
}}>
<Text style={{color:item?.checked ? 'green':'red'}}>
{`${item?.checked ? 'Checked':'UnCheked'} (click me to change)`}
<Text/>
</Pressable>
);
}}
/>