0

I have an object in React that I mapped and wanted to make it interact: I want it so when user clicks on the 'X' button next to an element, it would console.log the key of that clicked element.

Here is the object:

var obj = {
  person1: {
    name: 'iggy',
    superPower: 'awesomeness',
    favDonut: 'chocolate'
  },
  person2: {
    name: 'iggy2',
    superPower: 'stupendousness',
    favDonut: 'glazed'
  },
  person3: {
    name: 'iggy3',
    superPower: 'amazingness',
    favDonut: 'chocolate sprinkles'
  }
};

The iteration looks like this:

X chocolate
X glazed
X chocolate sprinkles

If I click the x on glazed, I want it to console.log person2 because that's the parent object of glazed. If I click x on chocolate sprinkles, I want it to console.log person3.

Here is the fiddle: https://jsfiddle.net/iggyfiddle/b9rreoje/2/

The method that I am trying to figure out is the getPersonName function. What is the best way to allow user to click on the x and console.log the relevant object key?

2 Answers 2

1

Rather than doing Object.values you'll want to do Object.keys, so you can then access the corresponding key.

  getPersonName: function(person){
    console.log(person);
  }

const donutValues = Object.keys(obj).map((key, index) => <li key={index}><a href="#" onClick={() => this.getPersonName(key)}>X</a> {obj[key].favDonut} </li>);

updated fiddle: https://jsfiddle.net/b9rreoje/3/

Sign up to request clarification or add additional context in comments.

1 Comment

Object.keys(obj)... while displays obj[key].favDonut. Didn't think of that. Thanks!!
0

You need to set onClick to an inline function that calls getPersonName with the corresponding person object.

  getPersonName: function(person){
    console.log(person);
  },

  render(){
    const donutValues = Object.values(obj).map((person, index) => <li key={index}><a href="#" onClick={function(){this.getPersonName(person)}.bind(this)}>X</a> {person.favDonut} </li>);
    return (
      <div>
        Hello 
          <ul>
            {donutValues}
          </ul>
          Give me person: {this.state.person}
      </div>
    );
  }

Find the updated jsfiddle here: https://jsfiddle.net/8637u8qL/

Comments

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.