How to target a specific element in react map loop - reactjs

I have comments that i loop through:
When i click on the three dots i want there to pop a little div out with the text "repport comment".
But when i click on one of buttons they all open :
import { FaEllipsisV } from "react-icons/fa";
import "./styles.css";
import React from "react";
const data = [
{
postId: 1,
id: 1,
name: "id labore ex et quam laborum",
email: "Eliseo#gardner.biz",
body:
"laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium"
},
{
postId: 1,
id: 2,
name: "quo vero reiciendis velit similique earum",
email: "Jayne_Kuhic#sydney.com",
body:
"est natus enim nihil est dolore omnis voluptatem numquam\net omnis occaecati quod ullam at\nvoluptatem error expedita pariatur\nnihil sint nostrum voluptatem reiciendis et"
},
{
postId: 1,
id: 3,
name: "odio adipisci rerum aut animi",
email: "Nikita#garfield.biz",
body:
"quia molestiae reprehenderit quasi aspernatur\naut expedita occaecati aliquam eveniet laudantium\nomnis quibusdam delectus saepe quia accusamus maiores nam est\ncum et ducimus et vero voluptates excepturi deleniti ratione"
},
{
postId: 1,
id: 4,
name: "alias odio sit",
email: "Lew#alysha.tv",
body:
"non et atque\noccaecati deserunt quas accusantium unde odit nobis qui voluptatem\nquia voluptas consequuntur itaque dolor\net qui rerum deleniti ut occaecati"
},
{
postId: 1,
id: 5,
name: "vero eaque aliquid doloribus et culpa",
email: "Hayden#althea.biz",
body:
"harum non quasi et ratione\ntempore iure ex voluptates in ratione\nharum architecto fugit inventore cupiditate\nvoluptates magni quo et"
}
];
export default function App() {
const [showOptions, setShowOptions] = React.useState(false);
return (
<div className="App">
{data.map((comment, index) => (
<div key={index} className="comment-container">
{comment.name}
<button onClick={() => setShowOptions(!showOptions)}>
<FaEllipsisV />
</button>
{showOptions ? (
<div className="options">Report this comment</div>
) : null}
</div>
))}
</div>
);
}
https://codesandbox.io/s/elated-roentgen-fbjr7?file=/src/App.js:0-2121
Example of what i'd like :

You can do something like this:
export default function App() {
const [showOptions, setShowOptions] = React.useState({ id: null, status: false });
return (
<div className="App">
{data.map((comment, index) => (
<div key={index} className="comment-container">
{comment.name}
<button onClick={() => setShowOptions({ id: comment.id, status: !showOptions.status })}>
<FaEllipsisV />
</button>
{showOptions.status && comment.id === showOptions.id ? (
<div className="options">Report this comment</div>
) : null}
</div>
))}
</div>
);
}

Related

Values not being mapped to object when getting element

What I want:
I want to get values for a JSON object declared like:
Tickets.json
[
{
"ticket_id": 13,
"user_id": 1,
"country_code": "+267",
"mobile_number": 74111111,
"email": "tdjlknds#sdmnnsd.com",
"policy_number": 7411235,
"category": "Unable to pay for cover",
"description": "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui",
"created_date": "2021/01/16 08:45:01",
"status": "IN PPROGRESS"
},
{
"ticket_id": 2,
"user_id": 2,
"country_code": "+267",
"mobile_number": 72654867,
"email": "tdjlknds#sdmnnsd.com",
"policy_number": 1243456,
"category": "Other",
"description": "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui",
"created_date": "2021/01/16 08:45:01",
"status": "WAITING CUSTOMER FEEDBACK"
}
]
And map it to an interface object in another .tsx file like this:
TicketCard.tsx
interface IViewTickets {
type: string;
userObj: {
ticket_id: number;
user_id: number;
country_code: string;
mobile_number: number;
email: string;
policy_number: number;
category: string;
description: string;
created_date: string;
status: string;
};
}
const TicketCard: React.FC<IViewTickets> = (props) => {
// some code
}
To do this I am using the below:
Dashboard.tsx
return (
<React.Fragment>
<div className="mainDashboardDiv">
<div id={`${styleId}`}>
{
Tickets.map(function (item, index) {
return ([
<DisplayList key={index} type="Open" userObj={item} />
]);
})
}
</div>
</div>
</React.Fragment>
)
I want to be able to use userObj to populate a the dashboard with all the json array items but I keep getting the error:
TypeError: Cannot read property 'policy_number' of undefined
I've tried a lot of things:
Using index or idx to pass on the index of an array
Rendering the json to an object array and using a loop to pass on values
adding a key value of the ID from the json
I keep getting the same error and console.log() shows that I'm not passing anything to the other file
Other ticketCard.tsx return define like:
return (
<Fragment>
<Card tokens={cardTokens} className="ticketCard animated fadeInLeft" compact={false}>
<Card.Item>
<Persona text={policy_string} secondaryText={tickets.created_date} />
</Card.Item>
<Card.Section>
<Text variant="small" styles={siteTextStyles}>
{tickets.category}
</Text>
<Text styles={descriptionTextStyles}>{tickets.ticket_id}</Text>
<Text variant="small" styles={helpfulTextStyles}>
{tickets.description}
</Text>
</Card.Section>
<Card.Section horizontal styles={footerCardSectionStyles} tokens={footerCardSectionTokens}>
<PrimaryButton className="cardButton" text={props.type} onClick={openTicketChat}/>
</Card.Section>
</Card>
</Fragment>
)
I just realized that I did it properly and the actual problem was that I called TicketCard.tsx instead of Dashboard.tsx.
When I fixed that issue, they showed up just fine.

Change position of objects inside an array

I have a functional component which has a useState that contains the information i want to display and the images.
const [images, setImages] = useState(
[
{
"index": 0,
"img": Volleyball,
"text": ' Lorem ipsum dolor, sit amet consectetur adipisicing elit. Libero ut dolorem dolore modi esse reprehenderit assumenda error aut ducimus, aliquam repudiandae aliquid deserunt voluptatum placeat fugit explicabo dignissimos cum tempore.'
},
{
"index": 1,
'img': Gaming,
"text": ' Lorem ipsum dolor, sit amet consectetur adipisicing elit. Libero ut dolorem dolore modi esse reprehenderit assumenda error aut ducimus, aliquam repudiandae aliquid deserunt voluptatum placeat fugit explicabo dignissimos cum tempore.'
},
{
'index': 2,
'img': Coding,
"text": ' Lorem ipsum dolor, sit amet consectetur adipisicing elit. Libero ut dolorem dolore modi esse reprehenderit assumenda error aut ducimus, aliquam repudiandae aliquid deserunt voluptatum placeat fugit explicabo dignissimos cum tempore.'
}
]
)
And this is the jsx that I have in the return body with a left button that prevImage function.
return (
<div className={classes.gallary}>
<div className={classes.direction}>
<button className={classes.leftArrow} onClick={prevImage}>Left</button>
<button className={classes.rightArrow} >Right</button>
</div>
<div className={classes.images}>
{images.map(current => {
return (
<div key={current.index}>
<img src={current.img} alt="" className={classes.image} />
</div>
)
})}
</div>
</div>
);
Here is the prevImage function :
const prevImage = () => {
const currentImgArray = [...images];
const sendToBack = currentImgArray.push(currentImgArray.pop());
setImages(sendToBack)
}
This is what it looks like before clicking the button and what I am trying to do is to place the first object as the last object in the array . If the function is called I get : "TypeError: images.map is not a function"
As has been pointed out, array::push returns the new length of the array, not an array. Basically you need to rotate the array left/right.
const prevImage = () => {
// moves last image to front of array
setImages(images => [images[images.length - 1], ...images.slice(0, -1)]);
};
const nextImage = () => {
// moves first image to end of array
setImages(images => [...images.slice(1), images[0]]);
};
Array.push returns new length of the array, so concat function is to be use on here:
const prevImage = () => {
const currentImgArray = [...images];
const sendToBack = currentImgArray.concat(currentImgArray.pop());
setImages(sendToBack)
}
Updated ans:
const prevImage = () => {
setImages(prevState => {const popArr = prevState.pop();
return prevState.concat(popArr);
})
}

How to fetch single data in Angularjs with Laravel5

I face an issue while retrieving single row/data from angular to html. I need to print the title. Below is the code of angular controller (partial):
vm.showJoke = function(joke){
console.log(joke);
$http.get('http://localhost:8000/api/v1/jokes/' + joke, {
//body: joke.joke,
//user_id: $rootScope.currentUser.id
//user_id: localstorageUser.role_id
}).success(function(response) {
//console.log(response.data.joke);
vm.jokes_show = response.data.joke;
console.log(vm.jokes_show);
$scope.MessageAll = 'Joke shows! ';
}).error(function(){
console.log("error");
$scope.MessageAll = 'Please try again';
});
}
Below is my HTML codes:
<span ng-hide="showEnabled">
<span class="glyphicon glyphicon-th-large" data-ng-click="jokes.showJoke(joke.joke_id)"></span>
</span>
<span ng-show="showEnabled" style="background-color:powderblue;">
<p style="background-color:powderblue;" ng-model="jokes_show"></p>
</span>
Here is the response I found below:
{joke_id: 3, joke: "Quia in enim voluptates neque. Ullam eligendi ipsu…iente qui perferendis libero. Ut aut qui sint et.", submitted_by: "admin"}
joke
:
"Quia in enim voluptates neque. Ullam eligendi ipsum eaque magni sit fugit in. Voluptate sapiente qui perferendis libero. Ut aut qui sint et."
joke_id
:
3
submitted_by
:
"admin"
See the image for the same too.
Your help most welcome.

How to update array of object in reactjs

I can't figure out how to change state in my app correctly. For example, I want change 'modalStatus' key of a particular post to true, what should I write in my showModal function? I have the following data-structure:
class App extends React.Component {
constructor() {
super();
this.state = {
posts: [
{
'author': 'Adolf Hitler',
'img': 'http://www.jewishvirtuallibrary.org/images/hitler1.jpg',
'content': 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
modalStatus: false
},
{
'author': 'Iosif Stalin',
'img': 'http://xn--h1aagokeh.xn--p1ai/wp-content/uploads/2016/07/46432404.jpg',
'content':'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
modalStatus: false
},
{
'author': 'Napoleon Bonapard',
'img':'http://cdn.history.com/sites/2/2015/04/hith-6-things-you-should-know-about-napoleon-E.jpeg',
'content':'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
modalStatus: false
},
{
'author': 'Vladimir Putin',
'img':'http://realnienovosti.com/images/148795554214.jpg',
'content':'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
modalStatus: false
}
]
};
And function that is responsible for changing the state:
showModal () {
this.setState(do something)
}
Write it like this, pass a index to this function whose value you want to edit,
showModal (index) {
var posts = JSON.parse(JSON.stringify(this.state.posts));
posts[index].modalStatus = true;
this.setState({posts});
}
Check the DOC.
Or You could use the update immutability helper for this:
this.setState({
posts: update(this.state.posts, {0: {modalStatus: {$set: true}}})
})
You can do it like that:
showModal () {
var item = this.state.posts[0];
item.modalStatus = true;
this.setState({});
}
After that - React will re-render your component according to new state object.

How to call single api in multiple react component with mixed up server side code?

Below is my nested object json, where i want access the properties in different react component
{
"Created":"2017-02-09",
"SenderOrReceiver":"Not developed yet",
"PageResponsible":"Yogesh Shinde",
"LastUpdated":"2017-02-09",
"ExternalLinks":[
{
"Id":null,
"Title":"Yahoo",
"Url":"http://yahoo.com"
},
{
"Id":null,
"Title":"Facebook",
"Url":"http://facebook.com"
}
],
"InternalLinks":[
{
"Id":null,
"Title":"Google",
"Url":"~/link/23199285feef4501987b5fa452e49b94.aspx"
}
],
"Appendices":[
{
"Id":null,
"Title":"React",
"Url":"~/link/23199285feef4501987b5fa452e49b94.aspx"
}
],
"ContactDetails":{
"Email":"user#gmail.com",
"Information":"Aliquam mollis, quam nec suscipit placerat, nibh est efficitur urna, in ornare mauris eros eu tortor. Nulla fermentum hendrerit mi, nec luctus nunc auctor at. Nullam sagittis posuere libero, eget imperdiet neque. Etiam ac lacus diam. Mauris sapien turpis, lobortis non eros in, porttitor dapibus ipsum.",
"Name":"user1",
"Telephone":"11234"
},
"Subject":[
"Lorem"
],
"HeadingLinks":[
{
"Id":"headinglink1",
"Title":"Heading1",
"Url":"/sv/news-page/#headinglink1"
}
]
}
Below is my server side index.cshtml (Layout)
#model intrav2.infrastructure.ViewModels.Pages.NewsPageViewModel
<div class="l-content_primary" role="main">
<div id="breadcrumb"></div>
<h2>#Html.PropertyFor(x => x.CurrentPage.Heading)</h2>
<div id="newcreatedinfo"></div>
<div>#Html.PropertyFor(x => x.CurrentPage.Media)</div>
<p class="preamble">#Html.PropertyFor(x => x.CurrentPage.Preamble)</p>
<div id="newsHeadingLinks"></div>
<p>#Html.PropertyFor(x => x.CurrentPage.MainBody)</p>
#Html.PropertyFor(x => x.CurrentPage.ExtraInformation)
<div id="newspagecontent"></div>
</div>
<aside class="l-blocks_secondary" role="complementary" id="newsSiderBar"></aside>
Now i want,
Created/SenderOrReceiver property in newcreatedinfo
External and Internal links in newspagecontent
Appendices/Contact in side content on page

Resources