vendredi 24 avril 2020

Why checkbox is not checking? (reactjs)

I have weird situation where my App component is working fine except for checking the checkbox, and the same App component, which I copy-paste in another project, is working totally fine. I created again new project with only App component, copy-pasted, same thing, everything is fine except checkbox. Can anyone explain to me what is going on here? How is it possible that the same component is working fine in one project and in others doesn't? And I restarted everything. So here is my code, just a simple to do list:

import React, { useRef, useReducer } from 'react'

function App() {

    const inputRef = useRef<HTMLInputElement>(null)

    const handleSubmit = (e: any) => {
        e.preventDefault()
        inputRef.current?.value !== "" && dispatch({ type: 'ADD_TODO', payload: inputRef.current?.value })
        inputRef.current && (inputRef.current.value = "")
    }

    const [todo, dispatch] = useReducer((state: any, action: any): any => {
        switch (action.type) {
            case 'ADD_TODO':
                return [...state, { id: state.length, name: action.payload, isCheck: false }]
            case 'CHECK_TODO':
                return state.filter((item: any, index: any):any => {
                    if (index === action.id) {
                        item.isCheck = !item.isCheck
                    }
                    return item
                })

        }
    }, [])

    const todos = todo.map((item: any, index: number) => {
        return (
            <li key={index}>
                <input type="checkbox" checked={item.isCheck} onChange={() => dispatch({ type: "CHECK_TODO", id: index })} />
                {item.name}
            </li>
        )
    })

    return (
        <div>
            <form onSubmit={handleSubmit}>
                <input
                    type="text"
                    placeholder="Buy milk"
                    ref={inputRef}
                />
            </form>
            <ul>{todos}</ul>
        </div>
    )
}

export default App

here, in some old project is working fine, I can check it and uncheck it: enter image description here

here, in any other new project is not working at all:

enter image description here

I didn't do anything unusual, created it with npx create-react-app . --template typescript

EDIT

Here is console log with snippet when clicked on checkbox 'eggs' (don't know why is it rendering twice, in project that works it's rendering only once):

case 'CHECK_TODO':
    return state.filter((item: any, index: any): any => {
        if (index === action.id) {
            item.isCheck = !item.isCheck
            console.log('click')
            console.log(`${index} === ${action.id}`)
            console.log(item.isCheck)
        }
        return item
    })

enter image description here




Aucun commentaire:

Enregistrer un commentaire