Home > Net >  React Native onpress one button id it gets coverted all the button into remove
React Native onpress one button id it gets coverted all the button into remove

Time:02-21

in react native suppose i have click on one add button but all the button gets converted to remove..id is unique only one item is added in console.. please let me know what can i do.. and along with suppose i press on add then it convert it to remove then again i want to click remove and it should go back to add but its not working...

// child component  



return (
<View key={crypto?.id} style={styles.container}>
 <Text style={styles.text} numberOfLines={1}> 
  {crypto.test_name</Text>
    <TouchableOpacity onPress={() => {
      
    props.status || false ? props.remove(crypto.id)   : props.add(crypto.id)   
    }}
    > 
    <Text style={styles.btn}>{props.status  || false ? "Remove" : 
     "Add"}</Text>
    </TouchableOpacity>

)

//parent component

const [status, setaddid] = React.useState(false);
const add = (crypto) => {

setmultipleTest((state) => [...state, crypto]);

setaddid( {status : true});}

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


  setaddid( {status : true});
}
  {filterdData.map((crypto, index) => (
            <Searchitems  key={index}   crypto={crypto}
              multipletest = {multipletest} 
              remove={(crypto) => remove(crypto)}
              add = {(crypto) => add(crypto)}
              />
     
      ))}

CodePudding user response:

You need to write all the state in parent components and then pass them to child components Something Like this

//In parent
const [multipletest, setmultipleTest] = React.useState([]);
const [status, setaddid] = React.useState(false);
const add = (crypto) => {

setmultipleTest((state) => [...state, crypto.id]);

setaddid( {status : true});}

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


      setaddid( {status : true});
    }
return (
<>
{filterdData.map((crypto, index) => (
            <Searchitems  key={index}   crypto={crypto}
              multipletest = {multipletest} 
              remove={(crypto) => remove(crypto)}
              add = {(crypto) => add(crypto)}
              />
     
      ))}
</>
  • Related