Reputation: 3765
I have a Gatsby Link
element inside of an <li>
and I want the Link
element to be triggered if the <li>
is clicked with cursor or hit with the enter
key.
export default class Search extends Component {
...Constructor...
render() {
...DOM elements...
<input type="text" value={this.state.query} onChange={this.search} placeholder={'Search'} />
{this.state.results.map((page, index) => (
<li tabIndex={index} key={page.id} >
<Link to={"/" + page.path}>{page.title}</Link>
</li>
))}
...DOM elements...
}
...More functions...
}
The above code is inside of a render
block, which is inside of a class which extends Component
.
I've tried adding an onClickHandler
to the <li>
, but don't know of any object I can pass to it which contains a reference to its child...
The main reason I need the event delegation to the child is because the tabIndex
(which receives focus from the input
element above it) only works on the <li>
, so once the <li>
has focus, I want the user to be able to hit enter and have that event propogate to the child <Link>
element (which is a special link element using Gatsby's internal routing).
Upvotes: 1
Views: 236
Reputation: 36945
You can pass the current page.path
as well as the event directly to your handler, onKeyPress={e => this.goTo(e, page.path)}
.
Example.
import { navigate } from "gatsby"
export default class Search extends Component {
... redacted for brevity ...
goTo = (e, path) => {
if (e.Key === "Enter") {
navigate(`/${path}`);
}
};
render() {
... redacted for brevity ...
{
this.state.results.map((page, index) => (
<li tabIndex={index} key={page.id} onKeyPress={e => this.goTo(e, page.path)}>
<Link to={"/" + page.path}>{page.title}</Link>
</li>
));
}
... redacted for brevity ...
}
}
Upvotes: 1