Click here to Skip to main content
15,880,427 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using two components in react. App.js and List.js
I need to use a useState function from App.js, in List.js
How can I achieve that ?

What I have tried:

I am building a basic CRUD to do list in react.
I want to delete individual tasks in it.

In App.js I am using this useState hook.

const [todos, setTodos] = useState(tasks);


I have a child component called List which maps out the lists of tasks.
In List.js I am writing the function to delete individual tasks:

const deleteTask = (id) => {
    const newTodoList = props.todos.filter((currTask) => {
      return currTask.id !== id;
    });
  };


Using the filter method I have removed the intended task to delete and the deleteTask function returns it. Now the problem is that I need to use setTodos from App.js in List.js.
Something like
setTodos(newTodoList)


How can I use a useState function (i.e. setTodos) in a different component ?
You can check my code in the codesandbox below:
CRUD-to-do-list - CodeSandbox[^]

I came across an answer but I am still getting erros in that:
https://www.pluralsight.com/guides/how-to-reference-a-function-in-another-component[^]
Posted
Updated 10-Jun-21 21:57pm

1 solution

React fuctional components don't have a this variable, so remove all references to it. In App.js you should have:
JavaScript
<List todos={todos} ts={setTodos} />

and in List.js:
JavaScript
const deleteTask = (id) => {
    const newTodoList = props.todos.filter((currTask) => {
      return currTask.id !== id;
    });

    props.ts(newTodoList);
};
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900