1

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?

5
  • What are you trying to achieve with this? Commented Jan 22, 2019 at 19:50
  • Do you have to do it that way? Can't name and value get their values from the same state/props? Commented Jan 22, 2019 at 19:52
  • @HemadriDasari updated the description for my exact use-case Commented Jan 22, 2019 at 20:01
  • 1
    Yes you can using event <Input controlId={"some_name"} onChange={(e) => this.props.someFunc(e.target.controlId)}/> Commented Jan 22, 2019 at 20:03
  • @stever I am trying to uniquely identify each component Commented Jan 22, 2019 at 20:52

1 Answer 1

1

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)}/>
Sign up to request clarification or add additional context in comments.

3 Comments

With onChange I can utilize the event object. Are there any similar such mechanisms for other attributes like value?
You can use document.getElementById or refs in react
Using document.getElementById will still result in using that Id in multiple places in the same component. I'm not sure how refs can be used here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.