Home > OS >  Passing Value to parent in React Native
Passing Value to parent in React Native

Time:10-13

To-Do List

I have a parent with a useState called tasks (array). And for each of those item (task) in array I am displaying a component with the item data and a delete button.

Now each component(child) has a delete button. But the array with the tasks is in the parent class so I can't delete the task or that component as the button is inside the component (child).

Any solutions for this problem?

CodePudding user response:

Firstly, in Parent component create remove function, and passed to child component, then use remove function in child component and pass index. For example, your code look like this:

import React from 'react';

function Todo({ todo, index, removeTodo }) {
    return (
        <div className="todo">
            <span>{todo.text}</span>
            <button onClick={() => removeTodo(index)}>Delete</button>
        </div>
    );
};

function App() {
    const [todos, setTodos] = React.useState([
        { text: "Learn about React" },
        { text: "Meet friend for lunch" },
        { text: "Build really cool todo app" }
    ]);

    const removeTodo = (index) => {

        let todosArrCopy = [...todos];

        todosArrCopy.splice(index,1);

        setTodos(todosArrCopy);
    }

    return (
        <div className="app">
            <div className="todo-list">
                {todos.map((todo, index) => (
                    <Todo
                        key={index}
                        index={index}
                        todo={todo}
                        removeTodo={removeTodo}
                    />
                ))}
            </div>
        </div>  
    );
}

export default App;

CodePudding user response:

You must declare the method called by the child component delete button in the parent, and pass it to the child component as a prop. in your main app.js:

    const deleteTask(index) {
        tasks_array.splice(index, 1);
    }
...

<ChildComponent handleDelete=deleteTask>
...

in ChildComponent.js:

const ChildComponent = (props) => {
    return (
        ...
        <Button className="copy-state-button" variant="primary" onClick={props.handleDelete}>
            Copy State to Clipboard
        </Button>
        ...

    );
}
  • Related