M
M
mosikus2019-11-30 18:22:47
React
mosikus, 2019-11-30 18:22:47

How to select an element of an object when clicking on a button and display it?

There is an object:

const test = {
   "title": {
       "t1":{
        "id": 1,
        "title":"Test1",
        "category": "Test1111"
        },
       "t2":{
        "id": 2,
        "title":"Test2",
        "category": "Test2222"
        },  
       "t3":{
     	  "id": 3,
        "title":"Test3",
        "category": "Test3333"
        }     
    }
}

I take it out:
{Object.keys(test.title).map(item => <div key={test.title[item].id}>{test.title[item].title} ---- {test.title[item].category}</div>)}
.
And now I need to solve the following problem:
There are 3 buttons. When you click on the first button, t1 is displayed, when you click on the second - t2, on the third - t3. How to do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-11-30
@mosikus

const [ active, setActive ] = useState(null);
const item = test.title[active];

const onClick = e => setActive(e.target.dataset.id);

Buttons:
{Object.keys(test.title).map(n =>
  <button key={n} data-id={n} onClick={onClick}>{n}</button>
)}

Selected item:
{item && <div>{item.title} ---- {item.category}</div>}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question