How to change a object state inside a map function - javascript

I need to increase or decrease state value in catalog > spec > units, if I click on increase button the number in units should increase by one and if I click on decrease button it should decrease by one, I'd tried by setting state in the render, but it didn't work and I think this is not a good practice. How can I create a function to setState of units without declaring it inside the render method?
Here is an example of my code:
export default class Order extends Component {
constructor(props) {
super(props);
this.state = {
catalog: [
{
photo: 'https://via.placeholder.com/400x400',
title: 'My title',
description: 'Bla bla bla...',
spec: { size: 'FAM', units: 1, price: 999999, id: 'CMB0', selectedIndicator: '', isSelected: false, name: 'A simple name' },
isCombo: true
},
],
}
}
}
render(){
return(
{this.state.catalog.map((item, index) => {
<div key={index}>
<strong>{item.title}</strong>
<span>{item.spec.units}</span>
<button onClick={() => item.spec.units + 1}>increase</button>
<button onClick={() => item.spec.units - 1}>decrease</button>
</div>})
}
)
}

Try this
increase = title => {
const newCatalogState = this.state.catalog.map(item => {
if (item.title === title) {
return {
...item,
spec: {
...item.spec,
units: item.spec.units + 1
}
};
}
return item;
});
this.setState({
catalog: newCatalogState
});
};
decrease = title => {
const newCatalogState = this.state.catalog.map(item => {
if (item.title === title) {
return {
...item,
spec: {
...item.spec,
units: item.spec.units - 1
}
};
}
return item;
});
this.setState({
catalog: newCatalogState
});
};
<button onClick={() => this.increase(item.title)}>increase</button>
<button onClick={() => this.decrease(item.title)}>decrease</button>
you can check here codesandbox hope it helps

Try this:
export default class Order extends Component {
constructor(props) {
super(props);
this.state = {
catalog: [
{
photo: 'https://via.placeholder.com/400x400',
title: 'My title',
description: 'Bla bla bla...',
spec: { size: 'FAM', units: 1, price: 999999, id: 'CMB0', selectedIndicator: '', isSelected: false, name: 'A simple name' },
isCombo: true
},
],
}
}
}
const updateUnits = (index, value) => {
const { catalog } = this.state
catalog[index].spec.units += value
this.setState({catalog})
}
render(){
return(
{ this.state.catalog.map((item, index) => {
<div key={index}>
<strong>{item.title}</strong>
<span>{item.spec.units}</span>
<button onClick={() => this.updateUnits(index, 1)}>increase</button>
<button onClick={() => this.updateUnits(index, -1)}>decrease</button>
</div>})
}
)
}

Related

Better way to access property in React.useState and update it?

I have a simple component that renders a menu with items. What I am trying to do is have a value called isLoggedIn that accesses the value of the Italian Food item, change it's value to true and later hide the Italian Food item. Currenly my code works, the Italian Restaurant item gets hidden, but is there a better way to access the available property, change it based on a condition and to hide the element? Here is my code:
import React, { useState, useEffect } from 'react';
import { withRouter } from 'react-router-dom';
import {
Drawer,
DrawerContent,
DrawerItem,
} from '#progress/kendo-react-layout';
import { Button } from '#progress/kendo-react-buttons';
const CustomItem = (props) => {
const { visible, ...others } = props;
const [isLoggedIn, setIsLoggedIn] = React.useState(
props.available ? false : true
);
const arrowDir = props['data-expanded']
? 'k-i-arrow-chevron-down'
: 'k-i-arrow-chevron-right';
React.useEffect(() => {
setIsLoggedIn(props.available);
}, [props.available]);
return (
<React.Fragment>
{isLoggedIn === false ? null : (
<DrawerItem {...others}>
<span className={'k-icon ' + props.icon} />
<span className={'k-item-text'}>{props.text}</span>
{props['data-expanded'] !== undefined && (
<span
className={'k-icon ' + arrowDir}
style={{
position: 'absolute',
right: 10,
}}
/>
)}
</DrawerItem>
)}
</React.Fragment>
);
};
const DrawerContainer = (props) => {
const [drawerExpanded, setDrawerExpanded] = React.useState(true);
const [items, setItems] = React.useState([
{
text: 'Education',
icon: 'k-i-pencil',
id: 1,
selected: true,
route: '/',
},
{
separator: true,
},
{
text: 'Food',
icon: 'k-i-heart',
id: 2,
['data-expanded']: true,
route: '/food',
},
{
text: 'Japanese Food',
icon: 'k-i-minus',
id: 4,
parentId: 2,
route: '/food/japanese',
},
{
text: 'Italian Food',
icon: 'k-i-minus',
id: 5,
parentId: 2,
route: '/food/italian',
available: false,
},
{
separator: true,
},
{
text: 'Travel',
icon: 'k-i-globe-outline',
['data-expanded']: true,
id: 3,
route: '/travel',
},
{
text: 'Europe',
icon: 'k-i-minus',
id: 6,
parentId: 3,
route: '/travel/europe',
},
{
text: 'North America',
icon: 'k-i-minus',
id: 7,
parentId: 3,
route: '/travel/america',
},
]);
const handleClick = () => {
setDrawerExpanded(!drawerExpanded);
};
const onSelect = (ev) => {
const currentItem = ev.itemTarget.props;
const isParent = currentItem['data-expanded'] !== undefined;
const nextExpanded = !currentItem['data-expanded'];
const newData = items.map((item) => {
const {
selected,
['data-expanded']: currentExpanded,
id,
...others
} = item;
const isCurrentItem = currentItem.id === id;
return {
selected: isCurrentItem,
['data-expanded']:
isCurrentItem && isParent ? nextExpanded : currentExpanded,
id,
...others,
};
});
props.history.push(ev.itemTarget.props.route);
setItems(newData);
};
const data = items.map((item) => {
const { parentId, ...others } = item;
if (parentId !== undefined) {
const parent = items.find((parent) => parent.id === parentId);
return { ...others, visible: parent['data-expanded'] };
}
return item;
});
return (
<div>
<div className="custom-toolbar">
<Button icon="menu" look="flat" onClick={handleClick} />
<span className="title">Categories</span>
</div>
<Drawer
expanded={drawerExpanded}
mode="push"
width={180}
items={data}
item={CustomItem}
onSelect={onSelect}
>
<DrawerContent>{props.children}</DrawerContent>
</Drawer>
</div>
);
};
export default withRouter(DrawerContainer);
If I understood your request properly you want to calculate the isLoggedIn property based on props.available, right? If this is correct then you may just use the useMemo hook in the following way:
const CustomItem = (props) => {
const { visible, ...others } = props;
const isLoggedIn = React.useMemo(() => {
return !props.available
});
const arrowDir = props['data-expanded']
? 'k-i-arrow-chevron-down'
: 'k-i-arrow-chevron-right';
return (
<React.Fragment>
{isLoggedIn === false ? null : (
<DrawerItem {...others}>
<span className={'k-icon ' + props.icon} />
<span className={'k-item-text'}>{props.text}</span>
{props['data-expanded'] !== undefined && (
<span
className={'k-icon ' + arrowDir}
style={{
position: 'absolute',
right: 10,
}}
/>
)}
</DrawerItem>
)}
</React.Fragment>
);
};
Here the doc of the hook if you want to go deeper.

Update state array by object Id

I want to update state array object by particular id.
Suppose I have following object in state. And I tried to update by following way using id but, it doesn't work for me.
It didn't update state data.
this.state = {
data: [{id:'124',name:'qqq'},
{id:'589',name:'www'},
{id:'45',name:'eee'},
{id:'567',name:'rrr'}]
}
publishCurrentProject = user => {
this.setState(prevState => ({
data: prevState.data.map(item =>
item.id === user.id ? { ...user } : item
),
}))
}
let user = {id:'124',name:'ttt'};
publishCurrentProject(user);
Any help would be greatly appreciated.
Maybe the problem is on how you called the publishCurrentProject(), maybe you put that function in the wrong context. I use your implementation and it still works
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [
{ id: "124", name: "qqq" },
{ id: "589", name: "www" },
{ id: "45", name: "eee" },
{ id: "567", name: "rrr" }
]
};
this.handleClick = this.handleClick.bind(this);
this.publishCurrentProject = this.publishCurrentProject.bind(this);
}
handleClick(e) {
let user = { id: "124", name: "ttt" };
this.publishCurrentProject(user);
}
publishCurrentProject(user) {
this.setState((prevState) => ({
data: prevState.data.map((item) =>
item.id === user.id ? { ...user } : item
)
}));
}
render() {
return (
<div className="App">
<h1>Test</h1>
{this.state.data.map((el) => (
<p>{el.name}</p>
))}
<button onClick={this.handleClick}>Change</button>
</div>
);
}
}
Codesandbox for worked example

React-data-grid - Changing cell value using global variable upon

I'm trying to create a certain functionality in my react-data-grid.
I have a column called subStart, and I have a dropdown that I want to use so that the user can set the value of a cell to the value of a state variable (this.state.timeTotalSec).
So if the user clicks on "Use Global Time" option in a 'Start Time' cell, it will replace the value of that cell with the value of this.state.timeTotalSec. How on earth do I do this?
I have the dropdown functionality working. But how do I get it to change the cell value?
const rows = [
{ id: 1, subStart: "00:00.000", subEnd: "00:00.000" , subText: 'Text1'},
{ id: 2, subStart: "00:00.000", subEnd: "00:00.000" , subText: 'Text2'},
{ id: 3, subStart: "00:00.000", subEnd: "00:00.000" , subText: 'Text3'}
];
const columns = [
{
key: "id",
name: "ID"
},
{
key: "subStart",
name: "Start Time",
editable: true
},
{
key: "subEnd",
name: "End Time",
editable: true
},
{
key: "subText",
name: "Text",
editable: true
}
].map(c => ({ ...c, ...defaultColumnProperties }));
const subStartActions = [
{
icon: <span className="glyphicon glyphicon-remove" />,
callback: () => {
alert("Deleting");
}
},
{
icon: "glyphicon glyphicon-link",
actions: [
{
text: "Use Global Time",
callback: () => {
// TODO
// **** TRYING TO MAKE THIS WORK ****
}
}
]
}
];
function getCellActions(column, row) {
const cellActions = {
subStart: subStartActions
};
return row.id % 2 === 0 ? cellActions[column.key] : null;
}
const ROW_COUNT = 50;
class App extends React.Component {
constructor (props) {
super(props)
this.state = {
playing: false,
duration: 0,
timeMilli: 0,
timeSec: 0,
timeMin: 0,
timeTotalSec: 0,
rows
}
}
onDuration = (duration) => {
this.setState({ duration })
}
onProgress = (progress) => {
if (this.state.duration == 0) {
return
}
const timeTotalSec = progress.played * this.state.duration
if (timeTotalSec !== this.state.timeTotalSec) {
const timeMin = Math.floor(timeTotalSec / 60)
const timeSec = Math.floor(timeTotalSec - (timeMin)*60)
const timeMilli = (timeTotalSec - timeSec - timeMin*60).toFixed(3)
this.setState({ timeTotalSec })
this.setState({ timeMin })
this.setState({ timeSec })
this.setState({ timeMilli })
}
}
onGridRowsUpdated = ({ fromRow, toRow, updated }) => {
this.setState(state => {
const rows = state.rows.slice();
for (let i = fromRow; i <= toRow; i++) {
rows[i] = { ...rows[i], ...updated };
}
return { rows };
});
};
render () {
const { data } = this;
return (
<div className='player-wrapper'>
<ReactPlayer
url='https://www.youtube.com/watch?v=lhlZkqEag7E'
className='react-player'
playing={this.state.playing}
onPlay={() => this.setState({ playing: true })}
onPause={() => this.setState({ playing: false })}
controls='True'
onDuration={this.onDuration}
onProgress={this.onProgress}
/>
Video is currently: {this.state.playing ? 'playing' : 'paused'}
<br />
Duration: {Math.round(this.state.duration).toString() + ' seconds'}
<br />
Elapsed: {this.state.timeMin + 'min ' + this.state.timeSec + 'sec ' +
this.state.timeMilli + 'ms'}
<br />
<button onClick={() => this.setState({ playing: true })}>Play</button>
<button onClick={() => this.setState({ playing: false })}>Pause</button>
<ButtonToolbar>
<Button variant="primary" onClick={() => this.setState(this.state.playing ? false : true)}>Play/Pause</Button>
</ButtonToolbar>
<ReactDataGrid
columns={columns}
rowGetter={i => this.state.rows[i]}
rowsCount={ROW_COUNT}
// minHeight={500}
getCellActions={getCellActions}
onGridRowsUpdated={this.onGridRowsUpdated}
enableCellSelect={true}
/>
</div>
)
}
}
ReactDataGrid will just render what data you pass to it, If you want to change the value of a cell, you should update the rows from data source or state you are using.in your case rows
this.state = {
playing: false,
duration: 0,
timeMilli: 0,
timeSec: 0,
timeMin: 0,
timeTotalSec: 10,
rows // your datasourse
};
I've supposed,id is your data Key.Add updateRowDate to actions to handle your state changes.
actions: [
{
text: "Use Global Time",
callback: () => {
// TODO
// **** TRYING TO MAKE THIS WORK ****
updateRowDate(row.id);
}
}
]
and here is updateRowDate in App component
updateRowDate = rowId => {
this.setState(prv => ({
rows: prv.rows.map(q => {
if (q.id === rowId) return { ...q, subStart: this.state.timeTotalSec };
return q;
})
}));
finally, you need to pass updateRowDate to getCellActions
<ReactDataGrid
columns={columns}
rowGetter={i => this.state.rows[i]}
rowsCount={ROW_COUNT}
// minHeight={500}
getCellActions={(column, row) =>
getCellActions(column, row, this.updateRowDate)
}
onGridRowsUpdated={this.onGridRowsUpdated}
enableCellSelect={true}
/>
Here is the temporary sandbox containing the fixed version

How do I add input data to JSON array in React.

I've been working on understanding React concepts and did my Todo project. I have the dummy data displaying, but can't add a new value to my dummy data, which is stored in an array of objects in a separate file, todos.js.
Here is the file hierarchy
Here is the error I am getting -
index.js:2177 Warning: Each child in an array or iterator should have a unique "key" prop.
TodoList.js
import React from 'react';
import Todo from './Todo';
import todos from '../todos'
class TodoList extends React.Component {
constructor() {
super();
this.state = {
todoItems: todos,
newItem: {}
}
}
addItem = (event) => {
event.preventDefault();
const todoList = this.state.todoItems;
todoList.push(this.state.newItem);
this.setState({
todoList: todos,
newItem: {}
});
};
handleInput = (event) => {
this.setState({ newItem: event.target.value });
}
render() {
const itenary = this.state.todoItems;
return (
<div>
{itenary.map(todo =>
<div key={todo.id}>
<Todo handleClick={this.props.handleClick} thing={todo} />
</div>
)}
<br />
<form onSubmit={this.addItem}>
<input type="text" onChange={this.handleInput} placeholder="Add a new task" />
<button>Submit</button>
</form>
</div>
);
}
}
export default TodoList;
Todo.js
import React from 'react';
class Todo extends React.Component {
constructor() {
super();
this.state = {
clicked: false
}
}
handleClick = () => {
this.setState({ clicked: !this.state.clicked });
}
render() {
const styles = this.state.clicked ? { textDecoration: 'line-through' } : { textDecoration: 'none' };
return (
{/* This is where the todo item is*/}
<div style={styles} onClick={this.handleClick} key={this.props.thing.id}>{this.props.thing.text}</div>
);
}
}
export default Todo;
todos.js
const todos = [
{ id: 1, text: 'Go to the gym', 'completed': false },
{ id: 2, text: 'Do laundry', 'completed': false },
{ id: 3, text: 'Study for exams', 'completed': false },
{ id: 4, text: 'Read a book', 'completed': false },
{ id: 5, text: 'Clean the bedroom', 'completed': false },
{ id: 6, text: 'Go to the park', 'completed': false },
];
export default todos;
Any help and/or feedback is appreciated.
You must give the new todo you add to todoItems a unique id that React can use to distinguish it from the others when you render them.
You should also not mutate the current state by using push. You should instead set state with an entirely new array that contains everything the previous one did.
Example
class TodoList extends React.Component {
constructor() {
super();
this.state = {
todoItems: todos,
newItem: ""
};
}
addItem = event => {
event.preventDefault();
this.setState(prevState => {
return {
todoItems: [
...prevState.todoItems,
{ id: Math.random(), text: prevState.newItem, completed: false }
],
newItem: ""
};
});
};
// ...
}
const todos = [
{ id: 1, text: "Go to the gym", completed: false },
{ id: 2, text: "Do laundry", completed: false },
{ id: 3, text: "Study for exams", completed: false },
{ id: 4, text: "Read a book", completed: false },
{ id: 5, text: "Clean the bedroom", completed: false },
{ id: 6, text: "Go to the park", completed: false }
];
class TodoList extends React.Component {
constructor() {
super();
this.state = {
todoItems: todos,
newItem: ""
};
}
addItem = event => {
event.preventDefault();
this.setState(prevState => {
return {
todoItems: [
...prevState.todoItems,
{ id: Math.random(), text: prevState.newItem, completed: false }
],
newItem: ""
};
});
};
handleInput = event => {
this.setState({ newItem: event.target.value });
};
render() {
const itenary = this.state.todoItems;
return (
<div>
{itenary.map(todo => (
<div key={todo.id}>
<Todo handleClick={this.props.handleClick} thing={todo} />
</div>
))}
<br />
<form onSubmit={this.addItem}>
<input
type="text"
onChange={this.handleInput}
value={this.state.newItem}
placeholder="Add a new task"
/>
<button>Submit</button>
</form>
</div>
);
}
}
class Todo extends React.Component {
constructor() {
super();
this.state = {
clicked: false
};
}
handleClick = () => {
this.setState({ clicked: !this.state.clicked });
};
render() {
const styles = this.state.clicked
? { textDecoration: "line-through" }
: { textDecoration: "none" };
return (
<div style={styles} onClick={this.handleClick} key={this.props.thing.id}>
{this.props.thing.text}
</div>
);
}
}
ReactDOM.render(<TodoList />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
You can always define the Object/s array within a function accepting an array:
In this example:
const [programs, setPrograms] = useState([]);
In order to create a single JSON program array:
setPrograms([{id: program?.id, title: program?.title}]);
How to create Array in JSON.
[ { "id": "1", "text": "Hello", "status": "false" }, { "id": "2", "text": "Coding Techniques", "status": "true" }, ]
Watch this video for more help
https://youtu.be/zgFOIdBIn4w

mapping an array of objects and changing the value with on onClick in React

I'm trying to change the value of like within the cardArr objects while using a map() to list each obj.
Below is my code.
Current, it works, but every object shares the same counter since it's not calling from the object. I understand that I'm currently just calling the object property stored in state, but how do I edit the like in each object using a map function?
import React, { Component } from 'react';
const cardArr = [
{
id: 1,
text: "Hey this is a test.",
img: " ",
like: 0
},
{
id: 2,
text: "If this works I'll call it a day.",
img: " ",
like: 0
},
{
id: 3,
text: "I'll drink a lot of beer.",
img: " ",
like: 0
},
{
id: 4,
text: "Cheers",
img: " ",
like: 0
}
]
export class Card extends Component {
constructor(props) {
super(props);
this.state = {
like: 0,
show: true
};
// this.handleClick = this.handleClick.bind(this);
}
IncrementItem = () => {
this.setState({ like: this.state.like + 1 });
}
DecreaseItem = () => {
this.setState({ like: this.state.like - 1 });
}
// handleClick(e) {
// e.preventDefault();
// this.IncrementItem();
// }
// handleClick(e) {
// e.preventDefault();
// this.DecreaseItem();
// }
render() {
const cardList = (cardArr.map((card) =>
<ul>
<li>
<div key={card.id}>
{card.text};
<img src={card.img}/>
<p>Like Button</p>
<button onClick={this.handleClickAdd}>Like</button>
<p>Dilike Button</p>
<button onClick={this.DecreaseItem}>Disike</button>
<p>Likes: {this.state.like}</p>
</div>
</li>
</ul>
));
return(
<div id='card'>
{cardList}
</div>
)
}
}
Move cardArr to your component's state so on each onClick (like or deslike) you will be able to change like prop as you want:
const Card = ({ card, onLike, onDeslike }) =>
<div>
{card.text}
<p>Likes: {card.like}</p>
<button onClick={() => onLike(card.id)}>Like</button>
<button onClick={() => onDeslike(card.id)}>Deslike</button>
</div>
class CardList extends React.Component {
constructor(props) {
super(props)
this.state = {
cards: [
{
id: 1,
text: 'Hey this is a test.',
img: ' ',
like: 0,
},
{
id: 2,
text: "If this works I'll call it a day.",
img: ' ',
like: 0,
},
{
id: 3,
text: "I'll drink a lot of beer.",
img: ' ',
like: 0,
},
{
id: 4,
text: 'Cheers',
img: ' ',
like: 0,
},
]
}
this.handleLike = this.handleLike.bind(this)
this.handleDeslike = this.handleDeslike.bind(this)
}
handleLike(id) {
this.setState(prevState => ({
...prevState,
cards: prevState.cards.map(card => ({
...card,
like: card.id === id ? card.like + 1 : card.like
}))
}))
}
handleDeslike(id) {
this.setState(prevState => ({
...prevState,
cards: prevState.cards.map(card => ({
...card,
like: card.id === id ? card.like - 1 : card.like
}))
}))
}
render() {
return (
<div>
<ul>
{this.state.cards.map(card =>
<li key={card.id}>
<Card
card={card}
onLike={this.handleLike}
onDeslike={this.handleDeslike}
/>
</li>
)}
</ul>
</div>
)
}
}
ReactDOM.render(
<CardList />,
document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Don't forget that setState is asynchronous and, therefore, you won't have it's latest changes right away.
What about to make separation. Create an additional component for cardAddr. And move the render and like working logic to CardAddr component.
const cardArr = [
{
id: 1,
text: "Hey this is a test.",
img: " ",
like: 0
},
{
id: 2,
text: "If this works I'll call it a day.",
img: " ",
like: 0
},
{
id: 3,
text: "I'll drink a lot of beer.",
img: " ",
like: 0
},
{
id: 4,
text: "Cheers",
img: " ",
like: 0
}]
class CardAddr extends React.Component {
constructor(props) {
super(props);
this.state = this.state = props.card;
}
IncrementItem = () => {
this.setState({ like: this.state.like + 1 });
}
DecreaseItem = () => {
this.setState({ like: this.state.like - 1 });
}
render() {
return (
<div key={this.state.id}>
{this.state.text}
<img src={this.state.img}/>
<p>Like Button</p>
<button onClick={this.IncrementItem}>Like</button>
<p>Dilike Button</p>
<button onClick={this.DecreaseItem}>Disike</button>
<p>Likes: {this.state.like}</p>
</div>
)
}
}
class Card extends React.Component {
constructor(props) {
super(props);
this.state = {
show: true
};
}
render() {
const cardList = (cardArr.map((card) =>
<ul key={card.id}>
<li>
<CardAddr card={card}/>
</li>
</ul>
));
return(
<div id='card'>
{cardList}
</div>
)
}
}
ReactDOM.render(
<Card />,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
</div>
Instead of pass the like in the state you have use your array and update the like of your element depending on the id.
import React, { Component } from 'react';
let cardArr = [
{
id: 1,
text: "Hey this is a test.",
img: " ",
like: 0
},
{
id: 2,
text: "If this works I'll call it a day.",
img: " ",
like: 0
},
{
id: 3,
text: "I'll drink a lot of beer.",
img: " ",
like: 0
},
{
id: 4,
text: "Cheers",
img: " ",
like: 0
}
]
export class Card extends Component {
constructor(props) {
super(props);
this.state = {
cardArr:cardArr
};
// this.handleClick = this.handleClick.bind(this);
}
IncrementItem = (id) => {
let cards = this.state.cardArr;
cards.find(c => c.id === id).like++;
this.setState({cardArr:cards});
}
DecreaseItem = (id) => {
let cards = this.state.cardArr;
cards.find(c => c.id === id).like--;
this.setState({cardArr:cards});
}
render() {
this.state.cardArr.map((card) =>
<ul>
<li>
<div key={card.id}>
{card.text};
<img src={card.img}/>
<p>Like Button</p>
<button onClick={(card.id) => this.handleClickAdd(card.id)}>Like</button>
<p>Dilike Button</p>
<button onClick={(card.id) => this.DecreaseItem(card.id)}>Dislike</button>
<p>Likes: {card.like}</p>
</div>
</li>
</ul>
);
return(
<div id='card'>
{cardList}
</div>
)
}
}

Categories