venni
venni

Reputation: 23

How to focus table row?

I try to set focus on the last row in my table when the user presses cmd+rightarrow. The user should in that way be able to choose any row element out of 8 without using a mouse. The keybinding works perfectly (and event listeners are added), but there is something wrong with the refs.

const selRef = useRef<any>();

const onKeyDown = (e) => {
    if ((e.ctrlKey || e.metaKey) && ['ArrowRight'].includes(e.key)) {
        selRef.current.focus();
    }

return (
                    <tbody>
                        {value.map((trip, index) => (
                            <div>
                                <tr
                                    onClick={() =>
                                        props.onSelect(trip, 'copy')
                                    }
                                    key={`history-row-${index}`}
                                    className={styles.focused}
                                    ref={selRef}
                                >
                                    <td id="sr-td-shortcut">{index + 1}</td>
                                    <td id="sr-td-pick">
                                        {genFormattedAddress(trip.start)}
                                    </td>
                                    <td id="sr-td-drop">
                                        {genFormattedAddress(trip.end)}
                                    </td>
                                </tr>
                            </div>
                        ))}
                    </tbody>
    )

Upvotes: 0

Views: 3913

Answers (1)

Oleksandr Kovalenko
Oleksandr Kovalenko

Reputation: 616

tr elements can not accepts focus by default. To enable focus behaviour, add tabindex={0} on <tr>

Upvotes: 3

Related Questions