Home > Net >  React native while adding one item id by onpress it adds all the item at once
React native while adding one item id by onpress it adds all the item at once

Time:02-16

can anyone tell me what can i do..i want to change the add button to remove button when one item added and again onpress remove ...add button will come..

function //

const [multipletest, setmultipleTest] = React.useState([]);
function addTest(crypto) {
setmultipleTest((state) => [...state, crypto.id]);}

map list //

{filterdData.map((crypto, index) => (
        <View key={index.toString()}>
              <TouchableOpacity onPress={() => addTest(crypto)}>
                {console.log(crypto, "crypto")}
                <Text> Add</Text>
              </TouchableOpacity>
        </View>

CodePudding user response:

This logic might help

function Example() {

  // default state
  const [multipletest, setmultipleTest] = React.useState([]);

  const add = (crypto) => {
    let newData = [...multipletest];
    newData.push(crypto.id);
    setmultipleTest(newData);
  }

  const remove = (crypto) => {
    let newData = [...multipletest];
    newData = newData.filter((e) => e !== crypto.id);
    setmultipleTest(newData);
  }

  // map list
  return filterdData.map((crypto, index) => {
    // check crypto id already exist or not
    const exists = multipletest.includes(crypto.id);
    return (
      <View key={index.toString()}>
        <TouchableOpacity
          onPress={() => {
            // handle onpress either add or remove as per condition
            exists ? remove(crypto) : add(crypto);
          }}
        >
          <Text>{exists ? "Remove" : "Add"}</Text>
        </TouchableOpacity>
      </View>
    );
  });
}
  • Related