Search code examples
reactjsreact-functional-component

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?


Solution

  • 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>
    )
    }