Mamuka Sakhelashvili
Mamuka Sakhelashvili

Reputation: 168

Access <a> tag inside onclick function in React

I have a React code where I put <a> tag with onClick function. When I click this component, inside the onClick function I want to get access to the <a> tag itself and set it's href value. Currently I do it like this:

render(): React.ReactNode {
    return (
        <a href='#' onClick={ () => this.clicked() } id = { 'btn_id' } />
    )
}

private clicked() {
    const a = document.getElementById("btn_id") as HTMLAnchorElement;

    a.href = "new_link";
}

This is working fine, but I don't want to use getElementById call to get access to the component. Is there any other way to do so?

Upvotes: 0

Views: 630

Answers (1)

Ernesto Stifano
Ernesto Stifano

Reputation: 3130

You don't need to use document.getElementById(). You can access the event targeted element from the event object as follows:

render(): React.ReactNode {
    return (
        <a href='#' onClick={ (e) => this.clicked(e) } id = { 'btn_id' } />
    )
}

private clicked(e) {
    const a = e.target as HTMLAnchorElement;

    a.href = "new_link";
}

Upvotes: 3

Related Questions