adrian
adrian

Reputation: 1

Unable to implement checkbox in Flatlist React Native

I got my JSON data API and wanted it to populate to the checkbox in the flatlist while the user is able to change the checkbox and send it back to the API call.

The problem is I am unable to create a working checkbox in the flatList using a functional component.

My studentAtt is either 0 or 1 from the database while checked means present (1), unchecked means absent(0).

This is how many data - classAtt looks like [{"studentID":"123","studentName":"User 1","studentAtt":0},{"studentID":"456","studentName":"User 2","studentAtt":0}]

import {CheckBox} from "react-native-elements";
const MarkAttendanceScreen = (props) => {
    const dispatch = useDispatch();
    const classAtt = useSelector(state => state.attendance.attendanceClass);
    const [attInfo,setAttInfo] = useState(JSON.stringify(classAtt));

    //fetch attendance
    const loadClassAtt = useCallback(async () => {
        let tempDate = new Date();
        let dateToDB = moment(tempDate).format('YYYY-MM-DD');
        try {
            await dispatch(attendanceActions.fetchClassAttendance(dateToDB));

        } catch (err) {
            setError(err.message);
        }

    }, [dispatch]);

    const updateAttendance = (id) =>{
        let temp = attInfo.map((info) => {
            if (id === info.studentID) {
                return { ...info, studentAtt: !info.studentAtt };
            }
            return info;
        });
        setAttInfo(temp);
    }

return(
   <FlatList
      onRefresh={loadClassAtt}
      refreshing={isRefreshing}
      data={classAtt}
      showsVerticalScrollIndicator={false}
      keyExtractor={(item, index) => index.toString()}
      extraData={classAtt}
      renderItem={({ item, index })=>(
            <AttendanceSign
                studentName={item.studentName}
                studentID={item.studentID}
            >

                  <CheckBox
                      checked={item.studentAtt}
                      onPress={() => updateAttendance(item.studentID)}
                   />


            </AttendanceSign>
          )}
  />
);

}

Hope to seek help from the experts on how to implement a working checkbox in flatlist RN

Upvotes: 0

Views: 227

Answers (1)

this.arjun
this.arjun

Reputation: 380

I am not sure why are you doing the JSON.stringify(classAtt)? anyways i have created a simple snack example of checkbox using flatlist for you :- https://snack.expo.dev/@arjunshukla97/a53a12

P.s:- This is just one of the many ways of implementing checkbox using flatlist. :)

Upvotes: 2

Related Questions