Reactive Data Display in React
Let's say we have an array of objects containing names and descriptions of something:
const initNotes = [
{
id: id(),
name: 'name1',
desc: 'long description 1'
},
{
id: id(),
name: 'name2',
desc: 'long description 2'
},
{
id: id(),
name: 'name3',
desc: 'long description 3'
},
];
Let's print each element of this array in a separate paragraph:
function App() {
const [notes, setNotes] = useState(initNotes);
const result = notes.map(note => {
return <p key={note.id}>
{note.name},
<i>{note.desc}</i>
</p>;
});
return <div>
{result}
</div>;
}
Now let's make it so that the description is initially hidden, but at the end of each paragraph we'll add buttons to show the description from this paragraph. To do this, we'll add the show
property to each product object, which controls the display of the description:
const initNotes = [
{
id: id(),
name: 'name1',
desc: 'long description 1',
show: false,
},
{
id: id(),
name: 'name2',
desc: 'long description 2',
show: false,
},
{
id: id(),
name: 'name3',
desc: 'long description 3',
show: false,
},
];
At the end of each paragraph, make a button that, when clicked, will display a full description of the product.