How to add index value in the list using React.js? - reactjs

I need to add index value in my data list using React.js. My code is below.
Itemlist.js:
import React, { Component } from "react";
class TodoItems extends Component {
constructor(props, context) {
super(props, context);
this.createTasks = this.createTasks.bind(this);
}
edit(key){
this.props.edit(key);
}
delete(key){
this.props.delete(key);
}
createTasks(item) {
return <li key={item._id}>{item.name}<a href="#" className="button bg_green" onClick={()=>this.edit(item._id)}>Edit</a><a href="#" className="button bg_red" onClick={()=>this.delete(item._id)}>Delete</a></li>
}
render() {
var todoEntries = this.props.entries;
var listItems = todoEntries.map(this.createTasks);
return (
<ul className="theList">
{listItems}
</ul>
);
}
};
export default TodoItems;
Todolist.js:
import React, { Component } from "react";
import TodoItems from "./TodoItems";
import "./TodoList.css";
import ItemService from './ItemService';
import axios from 'axios';
class TodoList extends Component {
constructor(props, context){
super(props, context);
this.state={
items:[]
}
this.addItem=this.addItem.bind(this);
this.deleteItem = this.deleteItem.bind(this);
this.editItem = this.editItem.bind(this);
this.ItemService = new ItemService();
}
componentDidMount(){
axios.get('http://localhost:8888/item')
.then(response => {
this.setState({ items: response.data });
})
.catch(function (error) {
console.log(error);
})
}
addItem(e){
e.preventDefault();
if(this.state.editKey){
this.saveEditedText();
return;
}
var itemArray = this.state.items;
if (this.inputElement.value !== '') {
itemArray.unshift({
text:this.inputElement.value,
key:Date.now()
})
this.setState({
items:itemArray
})
//console.log('items',this.state);
this.ItemService.sendData(this.inputElement.value);
this.divRef.insertAdjacentHTML("beforeend", '<p className="textcolor">'+this.inputElement.value+' has added successfully</p>');
this.inputElement.value='';
setTimeout( () => {
this.divRef.querySelector(':last-child').remove();
window.location.reload();
}, 3000);
}
}
saveEditedText(){
let value = this.inputElement.value;
this.setState(prevState => ({
items: prevState.items.map(el => {
if(el.key == prevState.editKey)
return Object.assign({}, el, {text: value});
return el;
}),
editKey: ''
}));
this.divRef.insertAdjacentHTML("beforeend", '<p className="textcolor">'+this.inputElement.value+' has updated successfully</p>');
this.inputElement.value='';
setTimeout( () => {
this.divRef.querySelector(':last-child').remove();
}, 3000);
}
render() {
return (
<div className="todoListMain">
<div className="header" id="parentDiv">
<div className="pageHeading" dangerouslySetInnerHTML={{ __html: "Todo Demo Application" }}></div>
<div className="wrapper">
<div ref={divEl => {
this.divRef = divEl;
}}></div>
<form onSubmit={this.addItem}>
<input ref={(a)=>this.inputElement=a} placeholder="enter task">
</input>
<button type="submit">{this.state.editKey? "Update": "Add"}</button>
</form>
<TodoItems entries={this.state.items} delete={this.deleteItem} edit={this.editItem}/>
</div>
</div>
</div>
);
}
}
export default TodoList;
Here after adding the data into db, the added data are shown in the list. Here I need to display the index value for each row means 1 - item1 like this.

You can do this by :
class TodoItems extends Component {
constructor(props, context) {
super(props, context);
this.createTasks = this.createTasks.bind(this);
}
edit(key){
this.props.edit(key);
}
delete(key){
this.props.delete(key);
}
render() {
var todoEntries = this.props.entries;
return (
<ul className="theList">
{todoEntries.map(this.createTasks, this)}
</ul>
);
}
createTasks(item, index) {
return (
<li key={item._id}>
{index} - {item.name}
<a href="#" className="button bg_green" onClick={()=>this.edit(item._id)}>Edit</a><a href="#" className="button bg_red" onClick={()=>this.delete(item._id)}>Delete</a>
</li>
)
}
};

If you mean to display index in ItemList component map has an overload which has paramater index that represents current index of element in array being processed.
See more in docs
So make createTasks(item, index){ } and then you will have access to index of the element.

Related

Array has duplicated records when using checkboxes to populate an array using React

I have trouble with simple task of adding elements selected in checkboxes to an array in component state. It seems like the push method for state.toppings (Editor.js) is invoked twice for each checkbox click, even though console.log shows that updateFormValueCheck method is invoked once per click. Can anyone help?
This is App.js
import React, { Component } from "react";
import { Editor } from "./Editor";
import { Display } from "./Display";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
formData: {}
}
}
submitData = (newData) => {
console.log("newData", newData)
this.setState({ formData: newData });
}
render() {
return <div className="container-fluid">
<div className="row p-2">
<div className="col-6">
<Editor submit={this.submitData} />
</div>
<div className="col-6">
<Display data={this.state.formData} />
</div>
</div>
</div>
}
}
This is Editor.js
import React, { Component } from "react";
export class Editor extends Component {
constructor(props) {
super(props);
this.state = {
toppings: ["Strawberries"]
}
this.toppings = ["Sprinkles", "Fudge Sauce",
"Strawberries", "Maple Syrup"]
}
updateFormValueCheck = (event) => {
event.persist();
this.setState(state => {
if (event.target.checked) {
state.toppings.push(event.target.name);
} else {
let index = state.toppings.indexOf(event.target.name);
state.toppings.splice(index, 1);
}
}, () => this.props.submit(this.state));
}
render() {
return <div className="h5 bg-info text-white p-2">
<div className="form-group">
<label>Ice Cream Toppings</label>
{this.toppings.map(top =>
<div className="form-check" key={top}>
<input className="form-check-input"
type="checkbox" name={top}
value={this.state[top]}
checked={this.state.toppings.indexOf(top) > -1}
onChange={this.updateFormValueCheck} />
<label className="form-check-label">{top}</label>
</div>
)}
</div>
</div>
}
}
This is Display.js
import React, { Component } from "react";
export class Display extends Component {
formatValue = (data) => Array.isArray(data)
? data.join(", ") : data.toString();
render() {
let keys = Object.keys(this.props.data);
if (keys.length === 0) {
return <div className="h5 bg-secondary p-2 text-white">
No Data
</div>
} else {
return <div className="container-fluid bg-secondary p-2">
{keys.map(key =>
<div key={key} className="row h5 text-white">
<div className="col">{key}:</div>
<div className="col">
{this.formatValue(this.props.data[key])}
</div>
</div>
)}
</div>
}
}
}
The output is:
You cannot directly mutate this.state, it can only be done using this.setState. For more info. refer this: Why can't I directly modify a component's state, really?
Therefore, you need to update your Editor component as follows.
componentDidMount is used to display the initial state during the initial rendering. Then componentDidUpdate is used to render the state changes through display component whenever it's updated.
import React, { Component } from "react";
export class Editor extends Component {
constructor(props) {
super(props);
this.state = {
toppings: ["Strawberries"],
};
this.toppings = ["Sprinkles", "Fudge Sauce", "Strawberries", "Maple Syrup"];
}
updateFormValueCheck = (event) => {
event.persist();
let data;
if (event.target.checked) {
data = [...this.state.toppings, event.target.name];
} else {
const index = this.state.toppings.indexOf(event.target.name);
const temp = [...this.state.toppings];
temp.splice(index, 1);
data = temp;
}
this.setState({
toppings: data,
});
};
componentDidMount() {
this.props.submit(this.state.toppings);
}
componentDidUpdate(prevPros, prevState) {
if (prevState.toppings !== this.state.toppings) {
this.props.submit(this.state.toppings);
}
}
render() {
console.log(this.state);
return (
<div className="h5 bg-info text-white p-2">
<div className="form-group">
<label>Ice Cream Toppings</label>
{this.toppings.map((top) => (
<div className="form-check" key={top}>
<input
className="form-check-input"
type="checkbox"
name={top}
value={this.state[top]}
checked={this.state.toppings.indexOf(top) > -1}
onChange={this.updateFormValueCheck}
/>
<label className="form-check-label">{top}</label>
</div>
))}
</div>
</div>
);
}
}
Hope this would be helpful to solve your issue.

Page not re-rendering after button click

I have a react class component which produces a product showcase using react-masonry. I now want to add filtering functionality with filter options displayed as buttons and on each click, the page elements should be filtered and the masonry display rerendered.
The filter functions work fine but I was not able to get the masonry to rerender.
import React from 'react'
import PropTypes from 'prop-types'
import Masonry from 'react-masonry-component'
import Product from 'components/Product'
const masonryOptions = {
transitionDuration: 0
};
class Gallery extends React.Component {
constructor (props){
super(props);
this.state ={
filter:props.filter,
elements:props.elements,
type:props.type,
}
this.handleFilterClick=this.handleFilterClick.bind(this)
}
handleFilterClick(filter){
console.log(filter)
this.setState({filter:filter})
console.log(this.state.filter)
}
filterProducts (elements,filter){
const filteredArray=elements.filter(function(el){
for (let i in el.tags) {
if (el.tags[i].slug===filter){
return true;
}
}
return false
})
return filteredArray;
}
renderGallery(){
const type=this.state.type
const elements=this.state.elements
var filter=this.state.filter
const filteredElements = elements
if (filter !=="*"){
const filteredElements = this.filterProducts(elements,filter)
}
const childElements = filteredElements.map(function(element,key){
if (element.mainPhoto!=null && element.isDogFood==type){
return (
<Product key={key} element={element}/>
);} else{
return null;
}
});
return (
<Masonry
className={'my-gallery-class'} // default ''
options={masonryOptions} // default {}
disableImagesLoaded={false} // default false
updateOnEachImageLoad={false} // default false and works only if disableImagesLoaded is false
>
<div className="col-md-12">
<ul className="filter text-center text-inline">
<li>
<button data-filter="*" className="selected">Tüm Ürünler</button>
</li>
<li>
<button filter="nograin">Tahılsız</button>
</li>
<li>
<button filter="seafood">Deniz Mahsülleri</button>
</li>
<li>
<button filter="poultry">Beyaz Et</button>
</li>
<li>
<button filter="redmeat">Kırmızı Et</button>
</li>
<li>
<button filter="pate" onClick={() =>{this.handleFilterClick("pate")}}>Püre</button>
</li>
</ul>
</div>
{childElements}
</Masonry>
);
}
render() {
return (
this.renderGallery()
)
}
}
Gallery.propTypes={
type: PropTypes.bool
}
export default Gallery
Use getDerivedStateFromProps instead of using props in constructor
import React from 'react'
import PropTypes from 'prop-types'
import Masonry from 'react-masonry-component'
import Product from 'components/Product'
const masonryOptions = {
transitionDuration: 0
};
class Gallery extends React.Component {
constructor (props){
super(props);
this.state = {
// Don't assign direct value in constructor as constructor function
// calls only at initialization
filter:props.filter,
elements:props.elements,
type:props.type,
}
this.handleFilterClick=this.handleFilterClick.bind(this)
}
getDerivedStateFromProps (props, prevState) {
if(//Put a valid condition) {
return {
filter: props.filter,
elements: props.elements,
type: props.type
}
}
return {}
}
handleFilterClick(filter){
console.log(filter)
this.setState({filter:filter})
console.log(this.state.filter)
}
filterProducts (elements,filter){
const filteredArray=elements.filter(function(el){
for (let i in el.tags) {
if (el.tags[i].slug===filter){
return true;
}
}
return false
})
return filteredArray;
}
renderGallery(){
const type=this.state.type
const elements=this.state.elements
var filter=this.state.filter
const filteredElements = elements
if (filter !=="*"){
const filteredElements = this.filterProducts(elements,filter)
}
const childElements = filteredElements.map(function(element,key){
if (element.mainPhoto!=null && element.isDogFood==type){
return (
<Product key={key} element={element}/>
);} else {
return null;
}
});
return (
<Masonry
className={'my-gallery-class'} // default ''
options={masonryOptions} // default {}
disableImagesLoaded={false} // default false
updateOnEachImageLoad={false} // default false and works only if disableImagesLoaded is false
>
<div className="col-md-12">
<ul className="filter text-center text-inline">
<li>
<button data-filter="*" className="selected">Tüm Ürünler</button>
</li>
<li>
<button filter="nograin">Tahılsız</button>
</li>
<li>
<button filter="seafood">Deniz Mahsülleri</button>
</li>
<li>
<button filter="poultry">Beyaz Et</button>
</li>
<li>
<button filter="redmeat">Kırmızı Et</button>
</li>
<li>
<button filter="pate" onClick={() =>{this.handleFilterClick("pate")}}>Püre</button>
</li>
</ul>
</div>
{childElements}
</Masonry>
);
}
render() {
return (
this.renderGallery()
)
}
}
Gallery.propTypes = {
type: PropTypes.bool
}
export default Gallery

How to pass function with argument in classname field in React?

I have following component in my React Project. What I want to do is to Add a className attribute to the <li> element. Set it equal to the return value of the getSortByClass() method and pass in sortByOptionValue as the argument.
import React from 'react';
import './SearchBar.css';
const sortByOptions = {
'Best Match': 'best_match',
'Highest Rated': 'rating',
'Most Reviewed': 'review_count'
}
function getSortByClass(sortByOption){
if (this.state.sortBy === sortByOption) {
return 'active';
}
else {
return '';
}
}
function handleSortByChange(sortByOption){
this.setState({
sortBy: sortByOption
});
}
export class SearchBar extends React.Component{
renderSortByOptions(){
return Object.keys(sortByOptions).map(sortByOption => {
let sortByOptionValue = sortByOptions[sortByOption];
return <li className={getSortByClass(sortByOptionValue)} key={sortByOptionValue}> {sortByOption} </li>;
});
}
constructor(props) {
super(props);
this.state = {
term: '',
location: '',
sortBy: 'best_match',
};
}
render(){
return (
<div className="SearchBar">
<div className="SearchBar-sort-options">
<ul>
{this.renderSortByOptions()}
</ul>
</div>
<div className="SearchBar-fields">
<input placeholder="Search Businesses" />
<input placeholder="Where?" />
</div>
<div className="SearchBar-submit">
<a>Lets Go</a>
</div>
</div>
);
}
}
export default SearchBar;
I am getting error: TypeError: Cannot read property 'state' of undefined after setting the classname field.
....
function getSortByClass(sortBy, sortByOption){
if (sortBy === sortByOption) {
return 'active';
}
else {
return '';
}
}
export class SearchBar extends React.Component{
handleSortByChange = (sortByOption) => this.setState({ sortBy: sortByOption});
renderSortByOptions(){
const that = this;
return Object.keys(sortByOptions).map(sortByOption => {
let sortByOptionValue = sortByOptions[sortByOption];
return <li className={getSortByClass(that.state.sortBy, sortByOptionValue)} key={sortByOptionValue}> {sortByOption} </li>;
});
}
....
Pass your state to the getSortByClass method as it doesn't have access to this because it is written outside the class. Also write handleSortByChange inside your class as it is accessing setState from this.
Also you can beautify the code as :
renderSortByOptions(){
const that = this;
return Object.keys(sortByOptions).map(sortByOption => {
let sortByOptionValue = sortByOptions[sortByOption];
return (
<li className={that.state.sortBy === sortOption ? 'active' : ''}
key={sortByOptionValue}
>
{sortByOption}
</li>
);
});
}

React JS - Event Handler in a dynamic list

I'm bringing a API s' content based on a dynamic list and I'm trying to apply a mouserEnter on each li. The event results by toggling content in the each list item. The event is working but it is toggling content in all the list items all at once, but I want it to toggle only the content that matches with the list item that is receiving the mouseEnter.
import _ from 'lodash';
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
export default class Dribbble extends React.Component {
constructor(props) {
super(props);
this.state = {
work: [],
hover: false
};
this.handleMouseEnter = this.handleMouseEnter.bind(this);
this.handleMouseLeave = this.handleMouseLeave.bind(this);
}
handleMouseEnter(){
this.setState({ hover: true })
}
handleMouseLeave(){
this.setState({ hover: false })
}
componentDidMount() {
this.ShotList();
}
ShotList() {
return $.getJSON('https://api.dribbble.com/v1/shots?per_page=3&access_token=41ff524ebca5e8d0bf5d6f9f2c611c1b0d224a1975ce37579326872c1e7900b4&callback=?')
.then((resp) => {
this.setState({ work: resp.data.reverse() });
});
}
render() {
const works = this.state.work.map((val, i) => {
return <li key={i} className="box"
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
>
{!this.state.hover ?
<div>
<img className="cover" src={val.images.normal} />
<div className="bar">
<h2>{val.title}</h2>
<span>{val.views_count}</span>
<i className="fa fa-eye fa-2x" aria-hidden="true"></i>
</div>
</div>
: null}
{this.state.hover ?
<div>
<h3>{val.user.name}</h3>
<img className="avatar img-circle" src={val.user.avatar_url}/>
<p>{val.description}</p>
</div>
:
null
}
</li>
});
return <ul>{works}</ul>
}
}
Here is my code:
There are couple of issues in your example, firstly as #aherriot states you should move the ul outside the map.
Next i would set this.state.hover to be the id of the item being hovered over on onMouseEnter.
The below snippet shows a basic example of this working that should be easy enough to adapt to your code.
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
items: [{id: 1, name: 'Fred'}, {id: 2, name: 'Albert'}, {id: 3, name: 'Jane'}],
hover: false,
}
this.handleMouseEnter = this.handleMouseEnter.bind(this);
this.handleMouseLeave = this.handleMouseLeave.bind(this);
this.renderItem = this.renderItem.bind(this);
}
handleMouseEnter(id){
console.log(`handleMouseEnter this.setState({ hover: ${id} })`);
this.setState({ hover: id })
}
handleMouseLeave(){
console.log('handleMouseLeave this.setState({ hover: false })');
this.setState({ hover: false })
}
renderItem(item, index) {
let content = [];
content.push(
<span>ID: {item.id}, Name: {item.name}</span>
);
if(this.state.hover === item.id) {
console.log('display " - hovering" for item id: ' + item.id);
content.push(
<span> - hovering</span>
);
}
return (
<li key={item.id}
onMouseEnter={() => this.handleMouseEnter(item.id)}
onMouseLeave={this.handleMouseLeave}
>
{content}
</li>
)
}
render() {
return <ul>
{this.state.items.map(this.renderItem)}
</ul>
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>
<div id="root"></div>
Maybe you should move the <ul> tag outside of this.state.work.map You only want one <ul> to show up, not one for each element.
You can place it at the bottom inside your div tag instead: return (<div><ul>{works}</ul></div>)

Unable to invoke props function passed to children in a loop reactjs

I am new to react. I am just trying to create a comment box and comment board which contain multiple comments.
Each comments have one inputbox, button(save,edit) and button(remove). I have passed function made in board named updateComment to Component Comment as props.
Now When I am trying to execute save of child function in which I have called parent function updateComment using this.props.updateComment
it is giving me error can't read property of undefined.
I have searched for similar question on stackoverflow but I am unable to solved this proplem.
My app.js code is as below.
import React from 'react';
import { Home } from './home.jsx';
class App extends React.Component {
render() {
return (
<div>
<Header/>
<Board />
</div>
);
}
}
class Header extends React.Component {
render() {
return (
<div>
<h1>Header</h1>
</div>
);
}
}
class Board extends React.Component {
constructor(props) {
super(props);
this.state = {
comments:[
"My name is brijesh",
"My name is santosh",
"My name is manoj"
]}
};
removeComment(i) {
console.log("going to remove element i",i);
var arr = this.state.comments;
arr.splice(i,1);
this.setState({comments:arr});
};
updateComment(newComment, i) {
var arr = this.state.comments;
arr[i] = newComment;
this.setState({comments:arr});
};
render() {
return (
<div className="board">
{
this.state.comments.map(function(text,i) {
return (
<Comment key ={i} index = {i}
updateComment={() => {this.updateComment}}
removeComment={() => {this.removeComment}}>
{text}
</Comment>
)
})
}
</div>
)
}
}
class Comment extends React.Component {
constructor(props) {
super(props);
this.state = {
edit: false
};
};
edit(){
this.setState({edit:true});
console.log("you clickced on edit0");
};
save(){
this.setState({edit:false});
var newText = this.refs.newText.value;
this.props.updateComment(newText, this.props.index);
console.log("you clickced on edit0",newText);
};
handleChange(event) {
this.setState({value: event.target.value});
}
render() {
if(this.state.edit) {
return (
<div>
<div className="comment">
<input type="text" ref="newText" defaultValue={this.props.children} onChange={ this.handleChange.bind(this) } />
<button onClick={this.save.bind(this)}>Save</button>
</div>
</div>
)
}
else {
return (
<div>
<div className="comment">
<div>{ this.props.children }</div>
<button onClick={this.edit.bind(this)}>Edit</button>
</div>
</div>
)
}
}
}
export default App
And my main.js looks like this.
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(
( < App / > ), document.getElementById('app'));
I have also created fiddle also.
https://jsfiddle.net/aubrijesh/k3h2pcnj/#&togetherjs=uEI7TFnJD1
I believe that DOMZE is on the right track but you should also bind the function in the map statement. In my opinion arrow functions makes it much easier to keep track of what this refers to.
class Board extends React.Component {
constructor(props) {
super(props);
this.state = {
comments:[
"My name is brijesh",
"My name is santosh",
"My name is manoj"
]}
};
removeCommment(i) {
console.log("going to remove element i",i);
var arr = this.state.comments;
arr.splice(i,1);
this.setState({comments:arr});
};
updateComment(newComment, i) {
var arr = this.state.comments;
console.log("new Comment");
arr[i] = newComment;
this.setState({comments:arr});
};
render() {
return (
<div className="board">
{
this.state.comments.map((text,i) => {
return (
<Comment key ={i} index = {i}
updateComment={() => {this.updateComment}}
removeComment={() => {this.removeComment}}>
{text}
</Comment>
)
})
}
</div>
)
}
}
class Comment extends React.Component {
constructor(props) {
super(props);
this.state = {
edit: false
};
};
edit(){
this.setState({edit:true});
console.log("you clickced on edit0");
};
save(){
this.setState({edit:false});
var newText = this.refs.newText.value;
this.props.updateComment(newText, this.props.index);
console.log("you clickced on edit0",newText);
};
handleChange(event) {
this.setState({value: event.target.value});
}
render() {
if(this.state.edit) {
return (
<div>
<div className="comment">
<input type="text" ref="newText" defaultValue={this.props.children} onChange={ this.handleChange} />
<button onClick={this.save.bind(this)}>Save</button>
</div>
</div>
)
}
else {
return (
<div>
<div className="comment">
<div>{ this.props.children }</div>
<button onClick={this.edit.bind(this)}>Edit</button>
</div>
</div>
)
}
}
}
ReactDOM.render(<Board />, document.getElementById("app"));
<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="app"></div>
update your render method
let self = this;
return (
<div className="board">
{
self.state.comments.map(function(text,i) {
return (
<Comment key ={i} index = {i}
updateComment={() => {self.updateComment}}
removeComment={() => {self.removeComment}}>
{text}
</Comment>
)
})
}
</div>
)
You need to bind the class to the function, so that it knows what "this" is
render() {
return (
<div className="board">
{
this.state.comments.map(function(text,i) {
return (
<Comment key ={i} index = {i}
updateComment={this.updateComment.bind(this)}
removeComment={this.removeComment.bind(this)}>
{text}
</Comment>
)
})
}
</div>
)
}
Note that you may want to do those bindings in the constructor so that it doesn't bind at each and every render

Resources