Home > Blockchain >  How to implement a list that has a behaviour of a checkbox
How to implement a list that has a behaviour of a checkbox

Time:03-29

I have a project that has a list of category

var category = [
{
    isSelected: false,
    title: "Meditation",
},

{
    isSelected: false,
    title: "Live Video",
},

]

this will display a list of Touchableopacity and when i click one it will change color and if i will click again it will go back to originall color

CodePudding user response:

Here's a link of it working (https://snack.expo.dev/S1v5KIJvi) and below I explain the code with code comments.

import * as React from 'react';
import { Text, View, TouchableOpacity } from 'react-native';


/* 
  Checkbox component
*/
const CheckBox = ({boxes,index,onPress})=>{
  return (
    <TouchableOpacity 
      onPress={onPress.bind(this,index)}
      style={{
        margin:10,
        width:50,
        height:50,
        backgroundColor:boxes[index].isSelected?"green":"black"
      }
    }>

    </TouchableOpacity>
  )
}

export default function App() {
  /* 
    Data to keep track of your boxes
  */
  const [boxes,setBoxes] = React.useState([
  {
      isSelected: false,
      title: "Meditation",
  },
  {
      isSelected: false,
      title: "Live Video",
  }]);


  /*
    Changes isSelected to true based on the index of the box
  */
  const onPress = (index)=>{
    const newBoxes = [...boxes];
    newBoxes[index].isSelected = !(newBoxes[index].isSelected)
    setBoxes(newBoxes)
  }




  return (
    <View style={{
      flex:1,
     justifyContent:"center",
     alignItems:"center",
    }}>
      {
        boxes.map((_,index)=>{
          return <CheckBox onPress={onPress} boxes={boxes}  index={index} key={index.toString()}/>
        })
      }
    </View>
  );
}

CodePudding user response:

export default function App() {

  const [category, setCategory] = useState([
    {
      isSelected: false,
      title: "Meditation",
    },
    {
      isSelected: false,
      title: "Live Video",
    },
  ])


  const handleItemPress = index => {
    // alert(index)
    const temp = category
    temp[index].isSelected = !category[index].isSelected
    setCategory(temp)
  }

  const renderItem = ({ item, index }) => {
    return (
      <TouchableOpacity
        onPress={() => handleItemPress(index)}
        style={{
          backgroundColor: item.isSelected == true ? 'tan' : null,
          height: 65,
          width: '90%',
          marginLeft: '5%',
          borderRadius: 10,
          borderColor: 'black',
          marginBottom: 10,
          borderWidth: 1,
          alignItems: 'center',
          justifyContent: 'center',
        }}>
        <Text>
          {item.title}
        </Text>

      </TouchableOpacity>
    )
  }

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <View style={{ flex: 1 }}>

        <FlatList
          data={category}
          keyExtractor={(item, index) => String(index)}
          renderItem={renderItem}
        />

      </View>
    </SafeAreaView>
  )
}

Notes

If you not getting updated from values after onPress e.g. onClick isSelected from false to true

I mean you get the updated value in logger but changes may not reflect in UI

then add one state

const [refresh, setRefresh] = useState()

and update that state value in handleItemPress() method

const handleItemPress = index => {
    const temp = category
    temp[index].isSelected = !category[index].isSelected
    setCategory(temp)
    setRefresh(Math.random())
  }

Like I am face this issue while making this example that's why I wrore this Notes

  • Related