A. L
A. L

Reputation: 12639

React: Accessing a target element as 'this'

This has probably been answered before, but I can't seem to google it as it overlaps a bit with .bind(this) questions.

What I want to do is to refer the calling element as this when I run a function e.g.

highlight()
{
  this.select();
}

<input value={final_line} onClick={this.highlight} ></input>

However, this is undefined after clicking it. So what would the best way to do this? Right now I'm using event.target as a replacement, which works. I've also seen ref being used, but am not sure if this is applicable as I am returning an array of input.

So my question overall is: Is there an alternative to using event.target?

Upvotes: 0

Views: 101

Answers (3)

corse32
corse32

Reputation: 166

Use call() inside an arrow function as your onClick to set this to event.target like:

onClick={ (event)=>{onClick.call(event.target, contact.id) }

Upvotes: 1

GG.
GG.

Reputation: 21844

So what would the best way to do this?

There is no way to do this. Using event.target is actually the right way to achieve it.

If you have several inputs, you should use the name property to identify the targeted element:

inputs.map(input =>
  <input name={input.name} onClick={this.highlight} />
)
highlight(event) {
  this.setState({ [event.target.name]: 'clicked!' })
}

Upvotes: 1

Vinay
Vinay

Reputation: 6322

I agree with GG. - you should use event.target, but an alternative is to use refs:

import { Component } from 'react';
import React from 'react';

class MyComponent extends Component {
  render() {
    const { final_line } = this.props;

    return <input value={final_line}
      onClick={ this.highlight.bind(this)}
      ref="inputToHighlight"
    />;
  }

  highlight() {
    this.refs.inputToHighlight.select();
  }
}

Upvotes: 1

Related Questions