const data = [{ "name": "lorem ipsum", "description": "description1", "company_name": "PT dapibus ", "company_slug": "pt-dapibus", "watchlist": true, "id": 1 },{ "name": "lorem ipsum2", "description": "description2", "company_name": "Google", "company_slug": "company_slug", "watchlist": true, "id": 2 }]
function RenderFeeds({ feeds, onAddToWatch, onRemoveFromWatch }) {
return (
<React.Fragment>{/* or any markup you want */}
{feeds.map((feed) => (
<div className="feed" key={feed.id}>
<h1>{feed.name}</h1>
<h2>{feed.company_name}</h2>
<h2>{feed.description}</h2>
<button
onClick={() =>
feed.watchlist
? onRemoveFromWatch(feed.id)
: onAddToWatch(feed.id)
}
>
{feed.watchlist ? 'Remove From watchlist' : 'Add to watchlist'}
</button>
</div>
))}
</React.Fragment>
);
}
function Feed() {
const [feeds, setFeeds] = React.useState([]);
React.useEffect(() => {
//receiving data, for example fetching data by ajax or whatever
setFeeds(data);
}, []);
const handleAddToWatch = (id) => {
// implement updating feeds, for example making an ajax request and getting new data
setFeeds((feeds) =>
feeds.map((feed) => ({
...feed,
watchlist: feed.id == id ? true : feed.watchlist,
}))
);
};
const handleRemoveFromWatch = (id) => {
// implement updating feeds, for example making an ajax request and getting new data
setFeeds(feeds =>
feeds.map((feed) => ({
...feed,
watchlist: feed.id == id ? false : feed.watchlist,
}))
);
};
return (
<RenderFeeds
feeds={feeds}
onAddToWatch={handleAddToWatch}
onRemoveFromWatch={handleRemoveFromWatch}
/>
);
}
ReactDOM.render(<Feed/>, document.getElementById('root'))
.feed{
border: 2px solid #ccc;
padding: 15px;
margin: 15px;
}
.feed h1{ margin: 0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>