Skip to content
Advertisement

Send data on key ‘Enter’ – React

I’m trying to send my fieldset when I press Enter, but my function does not return my console.log

Here is a fragment of my component :

{formIncomes === false && (
                        <div className="text-left flex justify-items-center relative">
                            <form onSubmit={handleAddIncome} className="m-auto">
                                <label htmlFor="newIncomeName"></label>
                                <input className="w-38 bg-gray-50 shadow-inner italic p-1 m-1 text-gray-500 text-xs" id="newIncomeName"
                                    name="newIncomeName"
                                    type="text"
                                    value={incomeCall}
                                    onChange={(e) => setIncomeCall(e.target.value)}
                                    onClick={handleClearIncomeCall}
                                />

                                <label htmlFor="newIncomeAmount"></label>
                                <input className="w-38 shadow-inner italic p-1 m-1 text-gray-500 text-xs" id="newIncomeAmount"
                                    name="newIncomeAmount"
                                    type="text"
                                    value={incomeNum}
                                    onChange={(e) => setIncomeNum(e.target.value)}
                                    onClick={handleClearIncomeNum}
                                />
                            </form>
                            <i onClick={handleAddIncome} className="absolute right-0 fas fa-check text-gray-400 hover:text-green-500 text-xs p-1 m-1"></i>
                        </div>
                    )}

Here is my function :

    const handleKeyPress = (e) => {
        if (e.key === 'Enter') {
            console.log('Enter pressed')
        }
    }

Why is my console.log not responding when I press enter on my page ?

Advertisement

Answer

You’re almost there, just replace onKeyPress with onKeyDown and it should work.

For enter, the keyCode will return 13. So you could

const handleKeyPress = (e) => {
    if (e.keyCode === 13) {
        console.log('Enter pressed')
    }
}

https://developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event

Advertisement