How to delete element onclick in Reactjs? - javascript

I have made CARD's which display's username. When I click on the delete button i.e cross or cancel button it should remove the CARD's from the tasklist here tasklist is state variable. I am using .map() method to iterate over each task and display it. I want to delete the task card of a particular user when I click on the red cross button (see screenshot) currently only the window appears saying -> are you sure you want to delete it if I click yes it should delete it.
Code:
import React, {Component} from "react";
export default class Tasks extends Component{
constructor(props){
super(props);
this.state = {
taskList:[],
taskName:"",
type:"classification",
datasetName:"",
allDatasets:[],
users:[],
names:[]
}
}
triggerDelete(task){
if(window.confirm("Are you sure you want to delete this task?")){
}
}
render(){
return(
<div className="tasks-wrap">
<h1 onClick={()=>{
this.props.history.push("/taskdetails");
}}>Your Tasks</h1>
{
this.state.taskList.map((task,index)=>{
return(
<div key={index} className="item-card" onClick={()=>{
window.sessionStorage.setItem("task",JSON.stringify(task));
this.props.history.push("/taskdetails/");
}}>
<div className="name">{task.name}</div>
<div className="sub">
<div className="type">Dataset: {task.dateSetName}</div>
<div className="members">{task.userList.length + " participants"}</div>
</div>
<div className="del-wrap" onClick={(e)=>{
e.stopPropagation();
e.preventDefault();
this.triggerDelete(task);
}}>
<img src={require("../../images/cancel.svg")}/>
</div>
</div>
);
})
}
</div>
</div>
</div>
</div>
)
}
}
How should I modify my triggerDelete() method? So that the particular card gets deleted.

Pass index of the deleting task to the triggerDelete function and then just remove that index from this.state.taskList array.
<div className="del-wrap" onClick={(e)=>{
e.stopPropagation();
e.preventDefault();
this.triggerDelete(task, index);
}}>
<img src={require("../../images/cancel.svg")}/>
</div>
And in triggerDelete function
triggerDelete(task, index){
if(window.confirm("Are you sure you want to delete this task?")){
let taskList = [...this.state.taskList]
taskList.splice(index, 1);
this.setState({taskList: taskList})
}
}

you need to write the logic to delete the task, its easier to do it if you pass the index of the task to triggerDelete. window.confirm returns a boolean value indicating whether OK or Cancel was selected (true means OK).
import React, {Component} from "react";
export default class Tasks extends Component{
constructor(props){
super(props);
this.state = {
taskList:[],
taskName:"",
type:"classification",
datasetName:"",
allDatasets:[],
users:[],
names:[]
}
}
triggerDelete(index){
if(window.confirm("Are you sure you want to delete this task?")){
this.setState(prevState => ({
taskList: [...prevState.taskList.slice(0, index), ...prevState.taskList.slice(index + 1)]
}))
}
}
render(){
return(
<div className="tasks-wrap">
<h1 onClick={()=>{
this.props.history.push("/taskdetails");
}}>Your Tasks</h1>
{
this.state.taskList.map((task,index)=>{
return(
<div key={index} className="item-card" onClick={()=>{
window.sessionStorage.setItem("task",JSON.stringify(task));
this.props.history.push("/taskdetails/");
}}>
<div className="name">{task.name}</div>
<div className="sub">
<div className="type">Dataset: {task.dateSetName}</div>
<div className="members">{task.userList.length + " participants"}</div>
</div>
<div className="del-wrap" onClick={(e)=>{
e.stopPropagation();
e.preventDefault();
this.triggerDelete(index);
}}>
<img src={require("../../images/cancel.svg")}/>
</div>
</div>
);
})
}
</div>
</div>
</div>
</div>
)
}
}

Related

i would like to make an individual process in a map function like toggle on click

i want to make a button toggle on each div i click in map function but the buttons toggle in
whole dives on one click (i want to make each click toggle abutton on only the div that i clicked not all of them) ...................................................................................................
import React,{Component} from 'react'
import './course.css'
import Downloadcourse from './../download/down.js'
import {Transition,animated} from 'react-spring/renderprops'
class Course extends Component{
constructor(){
super();
this.state={
search:'',
showcomponent:false,
};
}
updatesearch=(e)=>{
this.setState({search:e.target.value.substr(0,20)});
}
downtoggle=(index)=>{
this.setState({showcomponent:!this.state.showcomponent})
}
render(){
let filteredcontacts= this.props.corses.filter(
(item)=>{
return item.name.toLowerCase().indexOf(
this.state.search.toLowerCase()) !== -1 ;
}) ;
let length= this.props.corses.length;
const courselist=length ?(
filteredcontacts.map((item,index)=>{
return (
<div className="col-sm-3 cat" key={item.id}>
<div className="maincover" >
<div className="mainimg" onClick={this.downtoggle}>
</div>
<div className="maincorse">
<div className="row course-title">
<h1 className="course-Name">{item.name}</h1>
</div>
<div className="row course-title">
<button className="removeing" onClick={()=>{this.props.deleteing(index)}}>Remove
Course</button>
</div>
<div className="row download">
<Transition
native
items={this.state.showcomponent}
from={{ position: 'absolute', overflow: 'hidden', height: 0 }}
enter={[{ height: 'auto' }]}
leave={{ height: 0 }}>
{show=>show &&(props=>(
<animated.div style={props}>
<Downloadcourse />
</animated.div>
))}
</Transition>
</div>
</div>
</div>
</div>
)}
)) :(
<div className="no-content">
<h2>no content to show</h2>
</div>
)
return(
<div className="course">
<input type="text" className="input-search" onChange={this.updatesearch}/>
<span className="magnficant"> 🔍</span>
<div className="row category">
{courselist}
</div>
</div>
)
}
}
export default Course;
To make multiple elements toggleable you need to store each element's toggled state in some data structure. A javascript object ({}) comes in handy for this.
Convert this.state.showComponent from boolean to object
this.state={
search: '',
showComponent: {},
};
Use the index passed to toggle handler to update toggled state
downtoggle = (index) => {
this.setState(prevState => ({
showComponent: {
...prevState.showComponent, // <-- spread existing state
[index]: !prevState.showComponent[index], // <-- toggle value
},
}));
}
Ensure index is passed to the toggle handler
onClick={() => this.downtoggle(index)}
Check the toggled state for the transition component
<Transition
// ... other props
items={this.state.showComponent[index]} // <-- truthy/falsey
/>

Dynamically expand/collapse on click of header

I have a set of items that needs to be shown in the UI, like a header and list of items under it. There is a parent component where I am passing this data to a file that is shown below. Based on this the parent-child layout is shown. Now I need to expand/collapse based on the click of the header.
There is a class "open" and "close " that can be attached to the div. Based on it the it gets collapse/expands. The point is how do it item wise
Can someone help
import React from "react";
import Child from "./Child";
import Parent from "./Parent";
export default class Helper extends React.Component{
constructor(props: any) {
super(props);
this.state = {
parent:{},
children:{},
};
}
componentDidMount() {
this.setParentValue();
this.setChildValue();
}
render() {
const { parent, children } = this.state;
const { name } = this.props;
return (
<>
<div className="an-panel expand-panel expand-close">
<div className="an-panel-header">
<div className="title-holder">
<span className="toggle-icon far fa-plus-square" />
<span className="toggle-icon far fa-minus-square" />
<h5>{name}</h5>
</div>
<div className="action-holder">
<div className="status-holder">
<Parent
parent = {parent}
onSelect={this.handleParentClick}
/>
</div>
</div>
</div>
{children.map(({ id, name },id) => (
<div className="an-panel-body" key={id}>
<ul className="applications-list-holder">
<li>
<div className="name">{name}</div>
<div className="status">
<Child
children={children}
onSelect={this.setChildSwitchValue}
/>
</div>
</li>
</ul>
</div>
))}
</div>
</>
);
}
}
Ok let me explain it to you, here is your code
import React from "react";
import Child from "./Child";
import Parent from "./Parent";
export default class Helper extends React.Component{
constructor(props: any) {
super(props);
this.state = {
parent:{},
children:{},
navBarStatus: false,
};
}
componentDidMount() {
this.setParentValue();
this.setChildValue();
}
changeNavBar = (e, status)=>{
this.setState({navBarStatus: !status});
}
render() {
const { parent, children } = this.state;
const { name } = this.props;
return (
<>
<div className={`an-panel expand-panel ${this.state.navBarStatus ? "expand-open" : "expand-close"}`}>
<div className="an-panel-header" onClick={(e)=>this.changeNavBar(e, this.state.navBarStatus)}>
<div className="title-holder">
<span className="toggle-icon far fa-plus-square" />
<span className="toggle-icon far fa-minus-square" />
<h5>{name}</h5>
</div>
<div className="action-holder">
<div className="status-holder">
<Parent
parent = {parent}
onSelect={this.handleParentClick}
/>
</div>
</div>
</div>
{children.map(({ id, name },id) => (
<div className="an-panel-body" key={id}>
<ul className="applications-list-holder">
<li>
<div className="name">{name}</div>
<div className="status">
<ChildSetting
children={children}
onSelect={this.setChildSwitchValue}
/>
</div>
</li>
</ul>
</div>
))}
</div>
</>
);
}
}
You can see I have taken a new property in state navBarStatus. Based on navBarStatus value I am changing CSS class which will expand/close your attached div

Not able to display list items using map in reactjs?

I have a userlist which contains name and email id of each user. I want to display it using the .map() method on userlist state variable. I have created displayusers() function to display the users but I am getting failed to compile error.
Code:
import React, { Component } from 'react';
class App extends Component {
constructor(props){
super(props);
this.state = {
userlist:[
{'name':'Rohan Singh',
'email':'rohan#gmail.com'
},
{'name':'Mohan Singh',
'email':'mohan#gmail.com'
},
{'name':'Rakesh Roy',
'email':'rakesh#gmail.com'
},
{'name':'Sunil Shah',
'email':'sunil#gmail.com'
}]
}
}
displayusers(){
return this.state.userlist.map( user => {
return(
<div className="item-card">
<div className="sub">
<div className="type">Username: {user.name}</div>
<div className="members">Email: {user.email}</div>
</div>
<div className="del-wrap">
<img src={require("../../images/cancel.svg")}/>
</div>
</div>
);
})
}
render() {
return(
<div className="users-wrap">
<h1>Users</h1>
<div className="task-content">
<div className="user-wrap">
<div className="users">
{this.displayusers()}
</div>
</div>
</div>
</div>
);
}
}
export default App;
I think you forgot about adding a key attribute to the element and there's missing </div> closing tag in your map function.
See the corrected code:
displayusers(){
return this.state.userlist.map( user => {
return(
<div className="item-card" key={user.name}>
<div className="sub">
<div className="type">Username: {user.name}</div>
<div className="members">Email: {user.email}</div>
</div>
<div className="del-wrap">
<img src={require("../../images/cancel.svg")}/>
</div>
</div>
);
});
}
You need to bind your displayusers function to this. You can do that in the constructor.
Update your code as following:
import React, { Component } from 'react';
class App extends Component {
constructor(props){
super(props);
this.state = {
userlist:[
{'name':'Rohan Singh',
'email':'rohan#gmail.com'
},
{'name':'Mohan Singh',
'email':'mohan#gmail.com'
},
{'name':'Rakesh Roy',
'email':'rakesh#gmail.com'
},
{'name':'Sunil Shah',
'email':'sunil#gmail.com'
}]
};
this.displayusers = this.displayusers.bind(this); // you need to add this line
}
displayusers(){
return this.state.userlist.map((user, index) => {
return(
<div className="item-card" key={index}>
<div className="sub">
<div className="type">Username: {user.name}</div>
<div className="members">Email: {user.email}</div>
</div>
<div className="del-wrap">
<img src={require("../../images/cancel.svg")}/>
</div>
);
})
}
render() {
return(
<div className="users-wrap">
<h1>Users</h1>
<div className="task-content">
<div className="user-wrap">
<div className="users">
{this.displayusers()}
</div>
</div>
</div>
</div>
);
}
}
export default App;

How to add custom clickHandler for a specifc row

To set the context, I am new to REACT. I am working on a sample app where I need to display the trade data in tabular format. If you select the row, delete button on the extreme right should be displayed. Otherwise it should be hidden.
Instead of toggling with the display button, I am just trying to show and hide a text first. I was able to do that. Only thing which happens is that the text gets toggled for all the rows.
I was trying number of things to get this working. The code below is work in progress and I am not sure what to do next,
import React from 'react';
class TradeTableView extends React.Component {
constructor(){
super()
this.state = {
data: []
}
this.handleClickEvent = this.handleClickEvent.bind(this);
}
handleClickEvent(event) {
const name = event.target.name;
console.log('Name in handleClickEvent is ' + name);
}
componentDidMount() {
console.log('inside component did mount..');
fetch('http://localhost:3004/row')
.then(response => {
return response.json();})
.then(responseData => {console.log(responseData); return responseData;})
.then((data) => {
// jsonItems = JSON.parse(items);
this.setState({data: data});
});
}
render() {
return(
<div className="Table">
<div className="Heading">
<div className="Cell">
<p>Trade Date</p>
</div>
<div className="Cell">
<p>Commodity</p>
</div>
<div className="Cell">
<p>Side</p>
</div>
<div className="Cell">
<p>Quanity</p>
</div>
<div className="Cell">
<p>Price</p>
</div>
<div className="Cell">
<p>Counterparty</p>
</div>
<div className="Cell">
<p>Location</p>
</div>
<div className="Cell">
<p></p>
</div>
</div>
{this.state.data.map((item, key) => {
let prop1 = 'shouldHide'+key;
console.log('The prop is ' + prop1);
return (
<div ref={prop1} key={key} className="Row" onClick={this.handleClickEvent}>
<div className="Cell">
<p>{item.a}</p>
</div>
<div className="Cell">
<p>{item.b}</p>
</div>
<div className="Cell">
<p>{item.c}</p>
</div>
<div className="Cell">
<p>{item.d}</p>
</div>
<div className="Cell">
<p>{item.e}</p>
</div>
<div className="Cell">
<p>{item.f}</p>
</div>
<div className="Cell">
<p>{item.f}</p>
</div>
<div className="Cell">
<p onClick={this.handleClickEvent}>{this.state.prop1 ? 'Sample Text':'Some Text'}</p>
</div>
</div>
)
})}
</div>
);
}
}
export default TradeTableView;
This is my component. If you can let me know how to toggle the text only for a particular row, I can most probably use that know how to toggle the button(my original use case) and then delete the row on click of the button. I will really appreciate your help.
P.S I was able to toggle the text.You may not find logic on thi.state.prop1 in my code above because I was trying to modify the code to make it work for a single row. And finally I got in a state where it is not working for all the rows and obviously not for a single row. To sum up, my problem is to identify the unique row and dislay a section only for that row.
I've added a currentSelectedRow property to state to keep track of the selected row. Below is the code with minimal configuration.
import React from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
class TradeTableView extends React.Component {
constructor() {
super()
this.state = {
data: [{id:1,val:11},{id:2,val:22},{id:3,val:33}],
currentSelectedRow : -1
}
}
handleClickEvent = (event, key) =>{
this.setState({ currentSelectedRow: key})
}
render() {
return (
<div className="Table">
{this.state.data.map((item, key) => {
return (
<div key={key} className="Row" onClick={(e) => this.handleClickEvent(e, key)}>
<div className="Cell">
<p>{item.id}</p>
</div>
<div className="Cell">
<p>{item.val}</p>
</div>
<div className="Cell">
<p onClick={(e) => this.handleClickEvent(e, key)}>{this.state.currentSelectedRow === key ? 'Row Selected' : 'Row Not Selected'}</p>
</div>
</div>
)
})}
</div>
);
}
}
render(<TradeTableView />, document.getElementById('root'));
Here is the working example
Change your handleClickevent like this:
handleClickEvent(event, index) {
const name = event.target.name;
console.log("index is", index);
const stateData = [...this.state.data];
stateData[index]= "some new value"
this.setState({
data: stateData,
})
console.log('Name in handleClickEvent is ' + name);
}
change how you are attaching click handler to
onClick={(event) => this.handleClickEvent(event, key)}
Something along these lines is needed as per my understanding of the question.

Onclick event handler with passing this in reactjs

My component is as below:
import React, {PropTypes} from 'react';
export default class Viewdesc extends React.Component {
render() {
return (
<div className="col-md-12 slide-row">
<div className="col-md-12 overview-about-property">
<div className="expandabletext less">
<div className="col-md-12" dangerouslySetInnerHTML={{__html: this.props.record.ABOUT}}></div>
</div>
<div className="showmore"> Show More </div>
</div>
</div>
);
}
}
I want to call function say showmorefunct() passing clicked handler like this in jquery. How can I do this?
You can bind you function and pass params which you want, if you want to. You can do something like :
class Test extends React.Component {
handleClick(param, e){
console.log(e);
console.log(param);
}
render(){
return (
<div className="showmore" onClick={this.handleClick.bind(this, "Some param if you need it")}> Show More </div>
)
}
}
React.render(<Test />, document.getElementById('container'));
Here is fiddle.
UPDATE
http://jsfiddle.net/jwm6k66c/1517/
I don't quite really understand your question, but I imagine you want this-
import React, {PropTypes} from 'react';
export default class Viewdesc extends React.Component {
constructor(props) {
super(props)
this.showMoreFunct = this.showMoreFunct.bind(this)
}
showMoreFunct() {
alert('Show more clicked!')
}
render() {
return (
<div className="col-md-12 slide-row">
<div className="col-md-12 overview-about-property">
<div className="expandabletext less">
<div className="col-md-12" dangerouslySetInnerHTML={{__html: this.props.record.ABOUT}}></div>
</div>
<div className="showmore"> <span onClick={this.showMoreFunct}>Show More</span> </div>
</div>
</div>
);
}
}
You can replace span with a or button. You just need to specify the function you want to call to onClick prop. React will call it automatically when the user clicks on that span.

Categories

Resources