efthimio
efthimio

Reputation: 918

Access attribute value from another attribute in React

I have a React component for which I need to access an attribute from other attributes.

The use-case is having one of the attributes uniquely identify the component (controlId). The value attribute needs that id to know what to display from props, and the onChange attribute needs that id to tell the parent component how to update.

Currently, I can hardcode the Id in all three places.

<Input
    controlId={"someName"}
    value={this.props.fieldData["someName"]}
    onChange={(evnt) => this.props.handleFieldUpdate(evnt, "someName")}
/>

I have many components like this, and hardcoding strings like "someName" in multiple places is tedious and error prone. Is there a way to access the controlId attribute from the onChange and value attributes?

Upvotes: 1

Views: 1194

Answers (1)

Hemadri Dasari
Hemadri Dasari

Reputation: 33994

Use event.target To access the properties of an element. In your case to access controlId you can use event.target.controlId

   <Input controlId={"some_name"} onChange={event => this.props.someFunc(event.target.controlId)}/>

Upvotes: 1

Related Questions