Conditional Rendering in ReactJS Return section - javascript

I am looking for some help with conditional rendering inside of the return of my ReactJS page.
Here is what my code looks like:
import React from "react";
import NoActiveTracker from "../components/NoActiveTracker.js";
import NoCompletedTracker from "../components/NoCompletedTracker.js";
var bg = {
background: "#6F42C1"
}
class TrackerGeneralPage extends React.Component {
state = {
id: '',
active: [],
completed: [],
completedDateNow: '',
newStatus: 'Complete'
};
render() {
const { active, completed } = this.state
// if this.state.active.length > 0 ? { ---- I can do this with the return and set an else that will work fine but I am trying to do it for each table
return (
<>
<div>
{/* Active Trackers */}
<div id="toggle-active" className="">
<div className="my-4">
<table className="table table-hover table-bordered mb-3">
<thead className="thead-dark">
<tr>
<th scope="col" className="h5">Active</th>
<th scope="col">Name</th>
<th scope="col">Regulation</th>
<th scope="col">Due On</th>
<th scope="col">Assigned</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody>
{/* Need to perform conditional rending here with <NoActiveTrackers /> */}
{active.map(item => (
<>
<tr key={item.id}>
<th scope="row" className="dropdown">
<a className="btn btn-dark" data-toggle="collapse" href={"#a" + item.id} role="button" aria-expanded="false" aria-controls="item">Expand</a>
</th>
<td>{item.name}</td>
<td>{item.reg}</td>
<td>{item.dateDue}</td>
<td>{item.assigned}</td>
<td>{item.status}</td>
</tr>
<tr>
<td id={"a" + item.id} className="collapse hiddenRow" colSpan="6" rowSpan="1">
<div class="row">
<div class="col-sm">
<div class="card text-white text-center" style={bg}>
<div class="card-body">
<h5 class="card-title text-white font-weight-bold">Occurrence</h5>
<p class="card-text">{item.occurrence}</p>
<p>Next Expected Occurrence: Unknown</p>
</div>
</div>
</div>
<div class="col-sm">
<div class="card bg-light text-center">
<div class="card-body">
<h5 class="card-title font-weight-bold">Completed By</h5>
<p class="card-text">{item.completer} on {item.dateCompleted}</p>
<button className="btn btn-dark" onClick={() => this.handleUpdateTracker(item)} >Mark as Complete <img src="https://icon.now.sh/done_all/ffffff" width="25" height="25" className="d-inline-block align-top" alt="Complete Tracker" /></button>
</div>
</div>
</div>
<div class="col-sm">
<div class="card text-center">
<div class="card-body text-white bg-dark">
<h5 class="card-title text-white font-weight-bold">Description</h5>
<p class="card-text">{item.description}</p>
<button className="btn btn-light ml-1" onClick={() => this.handleDeleteTracker(item.id)} >Delete Tracker<img src="https://icon.now.sh/delete_forever" width="25" height="25" className="d-inline-block align-top" alt="Delete Tracker" /></button>
</div>
</div>
</div>
</div>
</td>
</tr>
</>
))}
</tbody>
</table>
</div> {/* End Table Section */}
</div> {/* End Active Toggle */}
{/* Completed Trackers */}
<div id="toggle-active" className="">
<div className="my-4">
<table className="table table-hover table-bordered mb-3">
<thead className="thead-dark">
<tr>
<th scope="col" className="h5">Completed</th>
<th scope="col">Name</th>
<th scope="col">Regulation</th>
<th scope="col">Due On</th>
<th scope="col">Assigned</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody>
{/* Need to perform conditional rending here with <NoCompleteTrackers /> */}
{completed.map(item => (
<>
<tr key={item.id}>
<th scope="row" className="dropdown">
<a className="btn btn-dark" data-toggle="collapse" href={"#a" + item.id} role="button" aria-expanded="false" aria-controls="item">Expand</a>
</th>
<td>{item.name}</td>
<td>{item.reg}</td>
<td>{item.dateDue}</td>
<td>{item.assigned}</td>
<td>{item.status}</td>
</tr>
<tr>
<td id={"a" + item.id} className="collapse hiddenRow" colSpan="6" rowSpan="1">
<div class="row">
<div class="col-sm">
<div class="card text-white text-center" style={bg}>
<div class="card-body">
<h5 class="card-title text-white font-weight-bold">Occurrence</h5>
<p class="card-text">{item.occurrence}</p>
</div>
</div>
</div>
<div class="col-sm">
<div class="card bg-light text-center">
<div class="card-body">
<h5 class="card-title font-weight-bold">Completed By</h5>
<p class="card-text">{item.completer} on {item.dateCompleted}</p>
</div>
</div>
</div>
<div class="col-sm">
<div class="card text-center">
<div class="card-body text-white bg-dark">
<h5 class="card-title text-white font-weight-bold">Description</h5>
<p class="card-text">{item.description}</p>
</div>
</div>
</div>
</div>
</td>
</tr>
</>
))}
</tbody>
</table>
</div> {/* End Table Section */}
</div> {/* End Completed Toggle */}
{/* Conditional Rendering Components are here just so I can visually seem them at the bottom of the page no matter way, will be removed once I figure out the conditional rendering of them */}
<NoActiveTracker />
<NoCompletedTracker />
</div> {/* End Container */}
</>
)
}
}
export default TrackerGeneralPage;
I can do if this.state.active.length > 0 ? { with the entire return ( and an else after that contains one of my components like NoActiveTrackers but since I have two tables, that means I would need a 4x if statement: one return if both trackers had items, one return if active had items but completed did not, one return if completed had items but active did not, and one return if both trackers did not have items.
How can I do conditional rendering directly before the map(s)?
Regards

Because you have 2 cases that have the same logic for displaying components, you can abstract this logic into a different component, for eg. a List component that takes your ListItem and NoItems as a prop and renders it.
const { render } = ReactDOM;
function Active() {
return <p>Definition of an active List item here</p>
}
function Completed() {
return <p>Definition of an active Completed item here</p>
}
function NoActive() {
return <p>No active list items to see here</p>
}
function NoCompleted() {
return <p>No completed list items to see here</p>
}
function List({
array,
listItem: ListItem, /*has start with capital letter */
noItems: NoItems,
}) {
if(array.length) {
return array.map((item, index) => <ListItem key={index} />);
} else {
return <NoItems />
}
}
function App() {
const activeItems = [1, 2];
const completedItems = [];
return (
<main>
<List array={activeItems} listItem={Active} noItems={NoActive} />
<List array={completedItems} listItem={Completed} noItems={NoCompleted} />
</main>
)
}
render(<App />, document.getElementById("root"))
<div id="root" />
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>

I think you are looking for something like this. active.length &&.
If active array is empty, active.map will not be run here.
{/* Need to perform conditional rending here with <NoActiveTrackers /> */}
{active.length && active.map(item => ( ...

Related

Multiple items not displaying in my Cart [ReactJS]

am building a small E-commerce site, where I want to display the cart details but when I try to add more than one item to the cart, only one item will displaying in cart page.
How I coded for displaying items in Cart:
I have a (Home Page) HomePage.jsx, where i will display the all the products through API. and i have a Button VIEW DETAILS for earch Items.
clicking on VIEW DETAILS button will navigate to Another jsx component i.e. ProductDetails.jsx, where i will display products details with ADD TO CART button, when we click on that button, it will send a props to Header.jsx component for displaying Cart badge at the top. as well as sending its product ID as a props to Cart.jsx.
When user visit Cart.jsx page, we will fetching its product details based on products ID[send by props prev. step]
Please checkout this samall video:click
There is Nothing problem in HomePage and ProductDetails page, only facing in Cart
Homepage.jsx - Home Page - Displaying all products from API through map()
<div className="row ">
{
items.myItems.map((itm,index)=>(
<div className="col-sm justify-content-between position-relative d-flex flex-column align-items-center text-center">
<img src={itm.image} id={`thummbnail_id${itm.id}`} alt="" height="300" width="300" className="text-center thumbnail" />
<h4>{itm.title}</h4>
<p>Rs.{itm.price}</p>
<li className="btn mb-5 btn-primary"><Link className="text-white" to={`/products-details/${itm.id}`}>VIEW DETAILS</Link></li>
</div>
))
}
</div>
ProductDetails.jsx - Product Details - Displaying particular product details
<div className="row">
{
initData1.products.map((item,index)=>
{
if(getId!=item.id)
{
return <div className="col-sm justify-content-between position-relative d-flex flex-column align-items-center text-center">
<p>{index}</p>
<p>{item.id}</p>
<img src={item.image} id={`thummbnail_id${item.id}`} alt="" height="300" width="300" className="text-center thumbnail" />
<h4>{item.title}</h4>
<p>Rs.{item.price}</p>
<li className="btn mb-5 btn-primary"><Link className="text-white" to={`/products-details/${item.id}`}>VIEW DETAILS</Link></li>
</div>
}
}
)}
</div>
Header.jsx - Header for displaying cart Badge
import {useState,React,useEffect} from 'react'
import {Link} from 'react-router-dom'
import '../../src/head_cont.css'
function Header(props) {
return (
<div className="head_cont">
<div className="container">
<div className="left">
<li className="logo text-light">SHOP69</li>
</div>
<div className="right">
<ul>
<li className="header_links mx-4"><Link className="link" to="/">HOME</Link></li>
<Link to="/"><i class="fas cart_icon cart_icon_resp pt-4 text-white fa-2x fa-home"></i></Link>
{/* <li className="header_links mx-4"><a className="link" href="#container_id">PRODUCTS</a></li> */}
<li className="header_links mx-4"><Link className="link" to="/cart-details">VISIT STORE</Link></li>
<Link to="/cart-details"><i className=" cart_icon pt-4 fa-2x fas text-light fa-shopping-bag"></i>{props.text>=1 ? <span className="badge" id="badge">{props.text}</span> : ""}</Link>
</ul>
</div>
</div>
</div>
)
}
export default Header
CartDeails.jsx - Cart Page
import React from 'react'
import { useState, useEffect } from 'react'
import '../../src/cart-details.css'
function CartDetails(props) {
const[cart,setCart]=useState([])
useEffect(() => {
try
{
let id=props.id
fetch(`https://fakestoreapi.com/products/${id}`).then(function(res){
return res.json();
}).then(function(data){
console.log(data)
setCart([...cart,data])
})
}
catch(err)
{
console.log("Something went wrong while fetching Cart items")
}
}, [])
if(props.val>=1)
{
return (
<div>
{cart.map((item,index)=>(
<div className="cart_cont text-dark">
<div className="innerDiv row m-auto mt-4 d-flex shadow-lg container">
<div className="d-flex justify-content-around align-items-center flex-column col-sm d-flex id">
<label htmlFor="id" className="text-danger fw-bold m-auto">ID</label>
<p className="m-auto" id="id">{item.id}</p>
</div>
<div className="d-flex col-sm thumbnail">
<img src={item.image} className="mt-1 mb-1" alt="image" height="100px" width="80px"/>
</div>
<div className="d-flex align-items-center flex-column col-sm quantity">
<label htmlFor="title" className="text-danger fw-bold m-auto">Title</label>
<p className="m-auto" id="title">{item.title}</p>
</div>
<div className="d-flex align-items-center col-sm flex-column unitPrice">
<label htmlFor="unitprice" className="text-danger fw-bold m-auto">Unit Price</label>
<p className="m-auto unitprice" id="unitprice">Rs. {item.price}</p>
</div>
<div className="d-flex align-items-center flex-column col-sm total">
<label htmlFor="total" className="text-danger fw-bold m-auto">Total</label>
<p className="m-auto total" id="total">N/A</p>
</div>
<div className="d-flex align-items-center col-sm rmBtn">
<i class="far fa-2x m-auto fa-trash-alt"></i>
</div>
</div>
</div>
))
}
</div>
)
}
else
{
return (
<div className="no_items">
<div className="no_items_bg text-center">
<h2 className="display-5 fw-bold">Cart is Empty</h2>
<i class="fas fa-5x fa-cat"></i>
</div>
</div>
)
}
}
export default CartDetails
As am familiar with React Functional Component and whole code is given here.
Please help me.
Thanks in advance.

How to use props inside map function in reactjs

I have created small function can't get props value, I am using map function but I could not send props used this props NewState={this.props.empname} could not send props this component ModalDelete. How do I solve this.
ViewEmpList.js
{this.props.filteredEmployee.map((emps, index) => {
return (
<tr key={index}>
<th scope="row">{emps.empid}</th>
<td>{emps.empname}</td>
<td>{emps.empid}</td>
<td>{emps.email}</td>
<td>{emps.mobile}</td>
<td style={{ color: "green" }}>
<div className="divtext">Active</div>
<div className="divshow"></div>
</td>
<td>
<BiEditAlt
className="fontcolor"
style={{ fontSize: 35 }}
/>
</td>
<td>
{/* <RiDeleteBin2Fill
className="fontcolor"
style={{ fontSize: 35 }}
/> */}
{/* <ModalDelete onClick={()=>{this.takeValue(emps)}}/> */}
<ModalDelete NewState={this.props.empname}/>
</td>
</tr>
);
})}
ModalDelete.js
<div className="modal fade col-md-12 col-sm-12" id="staticBackdrop" >
<div className="modal-dialog modal-dialog-centered ">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title btn-title" id="staticBackdropLabel">Are You sure want to delet it?</h5>
<TiDeleteOutline Style="color:#fff;font-size:18px;" type="button" />
</div>
<div className="modal-body">
{this.props.NewState}
</div>
<div className="modal-footer">
<button type="button" className="btn-delet" data-bs-dismiss="modal">Delete</button>
</div>
</div>
</div>

TypeError: Cannot read property 'map' of undefined - Shopping cart in reactjs

I'm writing a code for Shopping cart in react. Here is my code:
product-list/index.js
import React, {Component} from "react";
import "./index.css";
export default class ProductList extends Component {
// constructor() {
// super();
// }
render() {
return (
<div className="layout-row wrap justify-content-center flex-70 app-product-list">
{this.props.products.map((product, i) => {
return (
<section className="w-30"
data-testid={'product-item-' + i}
key={product.id}>
<div className="card ma-16">
<img alt="Your Cart" src={product.image}
className="d-inline-block align-top product-image"/>
<div className="card-text pa-4">
<h5 className="ma-0 text-center">{product.name}</h5>
<p className="ma-0 mt-8 text-center">${product.price}</p>
</div>
<div className="card-actions justify-content-center pa-4">
{product.cartQuantity===0 ?
<button className="x-small outlined" data-testid="btn-item-add"
onClick={()=>{this.props.add(product);}}>
Add To Cart
</button>
:
<div className="layout-row justify-content-between align-items-center">
<button className="x-small icon-only outlined"
data-testid="btn-quantity-subtract"
onClick={()=>this.props.sub(product)}>
<i className="material-icons">remove</i>
</button>
<input type="number"
disabled
className="cart-quantity" data-testid="cart-quantity" value={product.cartQuantity}/>
<button className="x-small icon-only outlined"
data-testid="btn-quantity-add" onClick={()=>this.props.add(product)}>
<i className="material-icons">add</i>
</button>
</div>
}
</div>
</div>
</section>
)
})}
</div>
);
}
}
export const UpdateMode = {
ADD: 1,
SUBTRACT: 0
}
cart/index.js
import React, { Component } from "react";
import "./index.css";
export default class Cart extends Component {
render() {
return (
<div className="card my-16 mr-25 flex-30">
<section className="layout-row align-items-center justify-content-center px-16">
<h4>Your Cart</h4>
</section>
<div className="divider" />
<table>
<thead>
<tr>
<th></th>
<th>Item</th>
<th className="numeric">Quantity</th>
</tr>
</thead>
<tbody>
{this.props.cart.items.map((cartItem, idx) => {
return (
<tr
data-testid={"cart-item-" + idx}
key={idx + 1}
className="slide-up-fade-in"
>
<td>{idx + 1}.</td>
<td className="name" data-testid="cart-item-name">
{cartItem.name}
</td>
<td
className="numeric quantity"
data-testid="cart-item-quantity"
>
{cartItem.cartQuantity}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}
}
This returns these errors:
TypeError: Cannot read property 'map' of undefined
ProductList.render
src/components/product-list/index.js:11
8 |
9 | render() {
10 | return (
11 |
| ^ 12 | {this.props.products.map((product, i) => {
13 | return (
14 | <section className="w-30"
TypeError: Cannot read property 'map' of undefined
Cart.render
src/components/cart/index.js:20
17 | Quantity
18 |
19 |
20 |
| ^ 21 | {this.props.cart.items.map((cartItem, idx) => {
22 | return (
23 | <tr
How can I fix this?
This is because when it tries to map, the data simply not available yet. You can add conditional rendering using && before the map function.
import React, {Component} from "react";
import "./index.css";
export default class ProductList extends Component {
// constructor() {
// super();
// }
render() {
return (
<div className="layout-row wrap justify-content-center flex-70 app-product-list">
{this.props.products && this.props.products.map((product, i) => {
return (
<section className="w-30"
data-testid={'product-item-' + i}
key={product.id}>
<div className="card ma-16">
<img alt="Your Cart" src={product.image}
className="d-inline-block align-top product-image"/>
<div className="card-text pa-4">
<h5 className="ma-0 text-center">{product.name}</h5>
<p className="ma-0 mt-8 text-center">${product.price}</p>
</div>
<div className="card-actions justify-content-center pa-4">
{product.cartQuantity===0 ?
<button className="x-small outlined" data-testid="btn-item-add"
onClick={()=>{this.props.add(product);}}>
Add To Cart
</button>
:
<div className="layout-row justify-content-between align-items-center">
<button className="x-small icon-only outlined"
data-testid="btn-quantity-subtract"
onClick={()=>this.props.sub(product)}>
<i className="material-icons">remove</i>
</button>
<input type="number"
disabled
className="cart-quantity" data-testid="cart-quantity" value={product.cartQuantity}/>
<button className="x-small icon-only outlined"
data-testid="btn-quantity-add" onClick={()=>this.props.add(product)}>
<i className="material-icons">add</i>
</button>
</div>
}
</div>
</div>
</section>
)
})}
</div>
);
}
}
export const UpdateMode = {
ADD: 1,
SUBTRACT: 0
}
import React, { Component } from "react";
import "./index.css";
export default class Cart extends Component {
render() {
return (
<div className="card my-16 mr-25 flex-30">
<section className="layout-row align-items-center justify-content-center px-16">
<h4>Your Cart</h4>
</section>
<div className="divider" />
<table>
<thead>
<tr>
<th></th>
<th>Item</th>
<th className="numeric">Quantity</th>
</tr>
</thead>
<tbody>
{this.props.card.items && this.props.cart.items.map((cartItem, idx) => {
return (
<tr
data-testid={"cart-item-" + idx}
key={idx + 1}
className="slide-up-fade-in"
>
<td>{idx + 1}.</td>
<td className="name" data-testid="cart-item-name">
{cartItem.name}
</td>
<td
className="numeric quantity"
data-testid="cart-item-quantity"
>
{cartItem.cartQuantity}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}
}
This should fix it.

toggle a specific div tag in an array

I am building a simple ReactJS app to fetch GitHub user and display
there repos. I am displaying the users in an array each have a details
button, onClick only that specific users div tag must be displayed. I
am able to pass username on click but onClick all users div tag are
toggling. I want to display repos on clicking the details button.
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import _ from 'lodash';
class SearchResults extends Component {
constructor(props) {
super(props);
this.state = { isOpen: false };
this.toggleDetails = this.toggleDetails.bind(this);
}
toggleDetails(userName) {
console.log(userName);
this.setState({ isOpen: !this.state.isOpen });
}
render() {
const { userList, userCount } = this.props;
const {isOpen} = this.state;
console.log('in searchResult = ' + this.props.userCount)
if (userList) {
var list = _.map(userList, (row, key) => {
return (
<div className="d-flex justify-content-center" key={row.id}
style={{ border: '0px solid red' }}>
<div className="card shadow-sm rounded" >
<div className="card-body ">
<div className="row ">
<div className="col-sm-2">
<img src={row.avatar_url} style={{ width: '80px', height: '80px' }}
className="rounded-circle" />
</div>
<div className="col-sm-10" style={{ border: '0px solid black' }}>
<h5 className="card-title"> {row.login}</h5>
<p className="display-6 text-muted"> {row.html_url} </p>
<button className="btn btn-outline-primary btn-sm float-right"
onClick={() => this.toggleDetails(row.login)} >
Details
</button>
</div>
</div>
</div>
{
isOpen &&
<table class="table table-striped" >
<tbody>
<tr>
<td>Otto</td>
<td>#mdo</td>
</tr>
<tr>
<td>Thornton</td>
<td>#fat</td>
</tr>
<tr>
<td>the Bird</td>
<td>#twitter</td>
</tr>
</tbody>
</table>
}
</div>
</div>
)
})
} else {
var list = (
<div className="d-flex justify-content-center ">
<div className="card shadow-sm rounded" >
<div className="card-body ">
<div className="row ">
No results to show
</div>
</div>
</div>
</div>
)
}
return (
<div className="user-list">
{userList ?
<div className="d-flex justify-content-center">
<div className="count">
<h6 className="display-6">Total Results : {userCount} </h6>
</div>
</div> :
<div className="d-flex justify-content-center">
<div className="count">
<h6 className="display-6">Total Results : {userCount} </h6>
</div>
</div>
}
{list}
</div>
)
}
}
export default SearchResults;
isOpen state is shared by all users. So you can try adding another state to keep the specific username which is open currently.
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import _ from 'lodash';
class SearchResults extends Component {
constructor(props) {
super(props);
this.state = { isOpen: false, currentUser : '' };
this.toggleDetails = this.toggleDetails.bind(this);
}
toggleDetails(userName) {
console.log(userName);
const currentUser = this.state.currentUser == userName ? '' : userName;
this.setState({ isOpen: !this.state.isOpen, currentUser:userName });
}
render() {
const { userList, userCount } = this.props;
const {isOpen, currentUser} = this.state;
console.log('in searchResult = ' + this.props.userCount)
if (userList) {
var list = _.map(userList, (row, key) => {
return (
<div className="d-flex justify-content-center" key={row.id}
style={{ border: '0px solid red' }}>
<div className="card shadow-sm rounded" >
<div className="card-body ">
<div className="row ">
<div className="col-sm-2">
<img src={row.avatar_url} style={{ width: '80px', height: '80px' }}
className="rounded-circle" />
</div>
<div className="col-sm-10" style={{ border: '0px solid black' }}>
<h5 className="card-title"> {row.login}</h5>
<p className="display-6 text-muted"> {row.html_url} </p>
<button className="btn btn-outline-primary btn-sm float-right"
onClick={() => this.toggleDetails(row.login)} >
Details
</button>
</div>
</div>
</div>
{
isOpen && currentUser === row.login &&
<table class="table table-striped" >
<tbody>
<tr>
<td>Otto</td>
<td>#mdo</td>
</tr>
<tr>
<td>Thornton</td>
<td>#fat</td>
</tr>
<tr>
<td>the Bird</td>
<td>#twitter</td>
</tr>
</tbody>
</table>
}
</div>
</div>
)
})
} else {
var list = (
<div className="d-flex justify-content-center ">
<div className="card shadow-sm rounded" >
<div className="card-body ">
<div className="row ">
No results to show
</div>
</div>
</div>
</div>
)
}
return (
<div className="user-list">
{userList ?
<div className="d-flex justify-content-center">
<div className="count">
<h6 className="display-6">Total Results : {userCount} </h6>
</div>
</div> :
<div className="d-flex justify-content-center">
<div className="count">
<h6 className="display-6">Total Results : {userCount} </h6>
</div>
</div>
}
{list}
</div>
)
}
}
export default SearchResults;

Error dynamically adding table rows in reactJs [duplicate]

This question already has answers here:
ES6 array map doesn't return anything: ReactJS
(2 answers)
Closed 4 years ago.
I am trying to create a reactJs page that allows an admin add a user to a platform. Now, instead of submitting the form for each new user, I want the admin to be able to add as many users as possible before submitting the form. By default, one table row containing input fields is displayed and then on click of the add button, a new row is added and the admin can fill the necessary details. However, I can't get my page to show the default row and the add button does not work either and unfortunately, my page throws no error. Here is my code:
export default class Admins extends React.Component{
constructor(props){
super(props);
this.state = {
errors : '',
success : '',
rows : [1]
}
this.addRow = this.addRow.bind(this);
this.fetchRows = this.fetchRows.bind(this);
}
addRow(){
var last = this.state.rows[this.state.rows.length-1];
var current = last + 1;
this.setState({
rows : this.state.rows.concat(current)
});
}
fetchRows(){
this.state.rows.map((row, index) => (
//console.log(row, index)
<tr key={row}>
<td className="text-center">
<button type="button" data-toggle="tooltip" className="btn btn-xs btn-danger"
data-original-title=""><i className="fa fa-trash"></i>
</button>
</td>
<td>
<input type="text" className="form-control"/>
</td>
<td>
<input type="text" className="form-control"/>
</td>
<td>
<input type="text" className="form-control"/>
</td>
</tr>
));
}
render(){
return(
<div>
<Top/>
<SideBar/>
<div className="breadcrumb-holder">
<div className="container-fluid">
<ul className="breadcrumb">
<li className="breadcrumb-item"><Link to="/">Dashboard</Link></li>
<li className="breadcrumb-item active">Admins</li>
</ul>
</div>
</div>
<section className="forms">
<div className="container-fluid">
<header>
<h3 className="h5 display">Admins</h3>
</header>
<div className="row">
<div className="col-lg-6">
<h5 className="text-danger">{this.state.errors}</h5>
<h5 className="text-success">{this.state.success}</h5>
</div>
</div>
<div className="row">
<div className="col-lg-6">
<div className="card">
<div className="card-header d-flex align-items-center">
<h5></h5>
</div>
<div className="card-body">
<table className="table table-bordered">
<thead>
<tr>
<th width="5%">Actions</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
</tr>
</thead>
<tbody>
{this.fetchRows()}
<tr>
<td className="text-center">
<button type="button" onClick={this.addRow} data-toggle="tooltip" className="btn btn-xs btn-primary"
data-original-title=""><i className="fa fa-plus"></i>
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
);
}
}
You are not returning anything from fetchRows. Return it or simply put it directly in the render method and it will work as expected.
Example
class Admins extends React.Component {
state = {
errors: "",
success: "",
rows: [1]
};
addRow = () => {
var last = this.state.rows[this.state.rows.length - 1];
var current = last + 1;
this.setState({
rows: this.state.rows.concat(current)
});
};
render() {
return (
<div>
<div className="breadcrumb-holder">
<div className="container-fluid">
<ul className="breadcrumb">
<li className="breadcrumb-item active">Admins</li>
</ul>
</div>
</div>
<section className="forms">
<div className="container-fluid">
<header>
<h3 className="h5 display">Admins</h3>
</header>
<div className="row">
<div className="col-lg-6">
<h5 className="text-danger">{this.state.errors}</h5>
<h5 className="text-success">{this.state.success}</h5>
</div>
</div>
<div className="row">
<div className="col-lg-6">
<div className="card">
<div className="card-header d-flex align-items-center">
<h5 />
</div>
<div className="card-body">
<table className="table table-bordered">
<thead>
<tr>
<th width="5%">Actions</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
</tr>
</thead>
<tbody>
{this.state.rows.map((row, index) => (
//console.log(row, index)
<tr key={row}>
<td className="text-center">
<button
type="button"
data-toggle="tooltip"
className="btn btn-xs btn-danger"
data-original-title=""
>
<i className="fa fa-trash" />
</button>
</td>
<td>
<input type="text" className="form-control" />
</td>
<td>
<input type="text" className="form-control" />
</td>
<td>
<input type="text" className="form-control" />
</td>
</tr>
))}
<tr>
<td className="text-center">
<button
type="button"
onClick={this.addRow}
data-toggle="tooltip"
className="btn btn-xs btn-primary"
data-original-title=""
>
<i className="fa fa-plus" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
);
}
}

Categories

Resources