Home > Software engineering >  Deleting list from another component in react
Deleting list from another component in react

Time:01-05

I'm falling a bit short on exactly how props work when trying to setState between different components in a "simple" way in parent-child or sibling components (without redux or context).

I've read the documentation, maybe I'm just supersuper slow in understanding this as I'm trying to self-learn react/coding, but can someone please explain the following in "simple" words:

  • in my parent.js I have all my logic for adding and removing a text and store it in a list
  • in my child.js which is a page created by the parent.js as a part of the list I want to be able to remove the whole listitem. Right now that logic is written in the parent.js, so I kinda want to access this function from my child component.

EDIT - I INCLUDED THE CODE FROM THE 2 MAIN COMPONENTS: EDIT 2 - TEST CODE THAT RETURNS "onRemove is not a function":

Home.js

const Home = ({navigation, route}) => {

const [lists, setLists] = useState([])
const [isVisible, setVisibility] = useState(true)

    const addItemToLists = (item) => {
        lists.push(item)
        setLists([...lists])
        setVisibility(false)
    }
    
    **const removeItemFromLists = (index) => {
        lists.splice(index,1) 
        setLists([...lists])
        console.log("removed")
        return(
            <EditList test={test} onRemove={removeItemFromLists}/>
        )
    }**
    
    const updateItemFromLists = (index,item) => {
        lists[index] = item
        setLists([...lists])
    }

return(

            <View style={styles.homeContainer}>

                <View style={styles.homeContainer2}>
                    <TouchableOpacity onPress={()=>navigation.navigate("Edit", {saveChanges: addItemToLists})}>
                        <Ionicons name="add-circle" size={60} color="black"/>
                    </TouchableOpacity>
                </View>


                <View style={{alignItems: 'center'}}>
                {!isVisible ? null : <Text>Add List-item</Text> }
                </View>

                <FlatList 
                data={lists}
                renderItem={({item: {title}, index})=>{
                    return(
                        <Listbutton 
                        title={title} 
                        navigation={navigation}
                        onPress={()=>{navigation.navigate("List", {title})}}
                        onOptions={()=>{navigation.navigate(
                            "Edit",
                            {title, saveChanges:(item)=>updateItemFromLists(index,item)})}}
                        onDelete={()=> removeItemFromLists(index)}
                        />
                    )
                }}
                />
                    
            </View>
    )
}

EditList.js

export default function EditList ({navigation, route,**test, onRemove**}){
    const [title, setTitle] = useState(route.params.title || "")
    const [isValid, setValidity] = useState(true)
    


    return(

    <View style={styles.editContainer}>
        <View>
     
        <TextInput
                    autoFocus={true} 
                    underlineColorAndroid={"transparent"}
                    selectionColor={"transparent"}
                    value={title}
                    onChangeText={(text)=>
                        {setTitle(text)
                            setValidity(true)
                        }}
                        placeholder={"Add header"}
                        maxLength={25}
                        style={styles.todoEditTextInput}
                        /> 

            <View style={{alignSelf: "center"}}> 
                {!isValid && <Text style={{color:"red"}}>Add list</Text>}
            </View>

             <TouchableOpacity
            style={{alignSelf: "center"}} 
            onPress={()=>{
                if (title.length > 0) {
                    route.params.saveChanges({title}) 
                    navigation.dispatch(CommonActions.goBack())
                } else {
                setValidity(false)
                }
            }}>
                <Ionicons name="checkmark-circle" size={50} style={{paddingLeft: 10,}}/>
            </TouchableOpacity>

        **<TouchableOpacity onPress={() => onRemove(test)}>
                 <Ionicons name="trash" size={50} style={{paddingLeft: 10,}}/>
        </TouchableOpacity>**

CodePudding user response:

You can pass a function as a prop to a component.

CodePudding user response:

So what you can do is pass your remove function as a prop to your child component, and call it when you want to execute it.

const ParentComponent = () => {

   const removeFromList = (someIdentifier) {
    // insert your list modification code here
   }

   return <ChildComponent someIdentifier={someIdentifier} onRemove={removeFromList} />

}

const ChildComponent = ({ someIdentifier, onRemove }) => (

 <TouchableOpacity onPress={() => onRemove(someIdentifier)} />  

)

I see you are using an index, so you could pass that in as your identifier - but please note that using indexes as keys is bad practice as you cannot guarantee that it will reference the same item in your list (especially now since you are removing items in a random order).

  •  Tags:  
  • Related