Yash Sharma
Yash Sharma

Reputation: 232

Updating a parent component's state on click on an element in child component

Parent Component :

const AddTodo = () => {
    const [todoList, setTodoList] = useState(['No active Todos'])


Child Component:

export const Todos = (props) => {
return (
<i class="material-icons close_icon">
clear
</i>
)

Now, the question is suppose todoList array has some items/todos or even if it's empty. So, how can I call the setTodoList function from child(Todos) component to update the todoList array on click of <i> element?

Upvotes: 1

Views: 531

Answers (1)

Murali Kollati
Murali Kollati

Reputation: 149

By passing setState as prop you achieve this:

Parent Component :

const AddTodo = () => {
    const [todoList, setTodoList] = useState(['No active Todos'])
    return(
        <div>
            {todoList}
            <Todos setTodoList={setTodoList}/>
        </div>
    )
}

Child Component:

export const Todos = ({setTodoList}) => {
return (
<i class="material-icons close_icon"
 onClick={()=>setTodoList("")}>
clear
</i>
)
}

Upvotes: 2

Related Questions