How to toggle a button in React list? - javascript

I render a React list and there is an Edit button in each list item. I wanted to toggle to switch from the data to the input form and back. Similar to this application in this article: https://medium.com/the-andela-way/handling-user-input-in-react-crud-1396e51a70bf. You can check out the demo at: https://codesandbox.io/s/fragrant-tree-0t13x.
This is where my React Component display the list:
import React, { Component } from "react";
import PriceBox from "../SinglePricebox/index";
// import SecurityForm from "../SecurityForm/index";
import AddPriceForm from "../AddPriceForm/index";
// import { uuid } from "uuidv4";
export default class PriceForm extends Component {
constructor(props) {
super(props);
this.state = {
priceArr: this.props.pricelist,
// newPriceArr: this.props.updatePrice,
showPricePopup: false,
addPricePopup: false,
isToggleOn: true,
date: props.date || "",
number: props.number || ""
};
}
updateInput = ({ target: { name, value } }) =>
this.setState({ [name]: value });
togglePopup = () => {
this.setState(prevState => ({
showPopup: !prevState.showPopup
}));
};
togglePricePopup = () => {
this.setState(prevState => ({
showPricePopup: !prevState.showPricePopup
}));
};
addPricePopup = () => {
this.setState(prevState => ({
addPricePopup: !prevState.addPricePopup
}));
};
/* adds a new price to the list */
addPrice = newPrice => {
this.setState(prevState => ({
addPricePopup: !prevState.addPricePopup,
// spreads out the previous list and adds the new price with a unique id
priceArr: [...prevState.priceArr, { ...newPrice }]
}));
};
// handlePriceSubmission = () => {
// const { updatePrice } = this.props;
// this.addPricePopup();
// updatePrice(priceArr);
// };
toggleItemEditing = (index) => {
this.setState(prevState => ({
priceArr: prevState.priceArr.map(priceItem => {
// isToggleOn: !state.isToggleOn;
})
}));
};
// toggleItemEditing = index => {
// this.setState({
// items: this.state.items.map((item, itemIndex) => {
// if (itemIndex === index) {
// return {
// ...item,
// isEditing: !item.isEditing
// }
// }
// return item;
// })
// });
// };
render() {
// const { updatePrice } = this.props;
return (
<div className="popup">
<div className="popup-inner">
<div className="price-form">
<h2>Prices</h2>
<div className="scroll-box">
{this.state.priceArr.map((props) => (
<PriceBox
{...props}
key={props.date}
// toggleItemEditing={this.toggleItemEditing()}
onChange={this.handleItemUpdate}
/>
))}
</div>
<div className="buttons-box flex-content-between">
<button
type="button"
onClick={this.addPricePopup}
className="btn add-button">Add +</button>
{this.state.addPricePopup && (
<AddPriceForm
addPrice={this.addPrice}
cancelPopup={this.addPricePopup}
/>
)}
<div className="add-btns">
<button
type="button"
onClick={() => this.props.closeUpdatePopup()}
className="btn cancel-button"
>
Close
</button>
</div>
</div>
</div>
</div>
</div>
);
}
}
The list inside the component above is:
<div className="scroll-box">
{this.state.priceArr.map((props) => (
<PriceBox
{...props}
key={props.date}
// toggleItemEditing={this.toggleItemEditing()}
onChange={this.handleItemUpdate}
/>
))}
</div>
And this is the single list item:
import React, { Component } from "react";
export default class SinglePricebox extends Component {
state = {
showPopup: false, //don't show popup
todaydate: this.props.date
};
/* toggle and close popup edit form window */
togglePopup = () => {
this.setState(prevState => ({
showPopup: !prevState.showPopup
}));
};
toggleEditPriceSubmission = getPriceIndex => {
const { toggleItemEditing, date } = this.props;
// toggle the pop up (close)
// this.showPopup();
toggleItemEditing({ ...getPriceIndex, date });
console.log("date?", date);
};
/* handles edit current security form submissions */
// handleEditSecuritySubmission = editSecurity => {
// const { editCurrentSecurity, id } = this.props;
// // toggle the pop up (close)
// this.togglePopup();
// // sends the editSecurity fields (name, isin, country) + id back to
// // App's "this.editCurrentSecurity"
// editCurrentSecurity({ ...editSecurity, id });
// };
render() {
return (
<div className="pricebox">
<article className="pricetable">
{this.toggleEditPriceSubmission
? "editing" : "not editing"}
<table>
<tbody>
<tr>
<td className="date-width">{this.props.date}</td>
<td className="price-width">{this.props.number}</td>
<td className="editing-btn">
<button
type="button"
className="edit-btn"
onClick={this.toggleEditPriceSubmission}
>
{this.toggleEditPriceSubmission ? "Save" : "Edit"}
</button>
</td>
<td>
<button
type="button"
className="delete-btn">
X
</button>
</td>
</tr>
</tbody>
</table>
</article>
</div>
);
}
}
I have been struggling all afternoon to toggle the edit button in each list item. I was attempting to get the key of each list item which is the this.prop.date.
You can see my code in detail at CodeSandBox: https://codesandbox.io/s/github/kikidesignnet/caissa

I would create a component which will handle the list item as a form and update it as if it was SecurityForm.
{this.state.priceArr.map((props) => {
if(props) {
return <PriceListForm methodToUpdate {...props} />
}else {
retun (
<PriceBox
{...props}
key={props.date}
// toggleItemEditing={this.toggleItemEditing()}
onChange={this.handleItemUpdate}
/>
);
}
})}
and make PriceListForm look like PriceBox but use inputs to capture new data. This way you will have two different components with less complicated logic instead of having a huge component with complex validations to check if you will display an input or not.

create a funtion named Edit to update the State
Edit = (id) => {
this.setState({edit: !this.state.edit, id})
}
and instead of that
<td className="country-width">{this.props.country}</td>
do something like
<td className="country-width">{this.state.edit ? <input type="text" value={this.props.country} onChange={() => UPDATE_THE_CONTENT}/> : this.props.isin}</td>
and call the Edit function onclick of Edit Button and pass ID of that td as a param to update it.
NOTE: by default THE VALUE OF EDIT STATE is false/null.
you can use onChange to update that box or some other techniques like create a button along with it and use that to update it.
hope this might help you

Related

display button upon typing input react

I want to be able to type into my input fields, and then have a button show up beside it upon typing that says submit edit. right now, I have a button that always is there, but I want it to only show up upon typing. this is all in react btw. so far, I have tried jquery, but react doesn't like it.
here's the whole page, to avoid any confusion of what I am doing and where my stuff is located.
import React, { Component } from "react";
import axios from "axios";
import "../styles/TourPage.css";
class TourPage extends Component {
constructor(props) {
super(props);
this.state = {
myData: [],
isLoading: true,
};
}
componentDidMount() {
axios
.get("/getResults")
.then((res) => {
this.setState({
myData: res.data
});
})
.catch((error) => {
// Handle the errors here
console.log(error);
})
.finally(() => {
this.setState({
isLoading: false
});
});
}
deleteById = (id) => {
console.log(id)
axios
.post(`/deleteDoc`, {id: id} )
.then(() => {
console.log(id, " worked")
window.location = "/tour"
})
.catch((error) => {
// Handle the errors here
console.log(error);
})
}
editById = (id, siteLocation, Services, cnum) => {
console.log(id, siteLocation, Services, cnum)
axios
.post(`/editDoc`, JSON.stringify({id: id, location: siteLocation, Services: Services, cnum: cnum}),{
headers: {
"Content-Type": "Application/json"
}
} )
.then(() => {
console.log(id, " worked")
window.location = "/tour"
})
.catch((error) => {
// Handle the errors here
console.log(error);
})
}
render() {
// You can handle the loader part here with isLoading flag. In this case No data found will be shown initially and then the actual data
let { myData, isLoading } = this.state;
return (
<table id="customers">
<tr>
<th>siteLocation</th>
<th>Services</th>
<th>cnum</th>
</tr>
{myData.length > 0
? myData.map(({ location, Services, cnum, _id }, index) => (
<tr key={index}>
<td><input type="text" placeholder={location} name="location" id="location" /> </td>
<td><input type="text" placeholder={Services} name="Services" id="Services" /> </td>
<td><input type="text" placeholder={cnum} name="cnumhide" id="cnumhide" /> </td>
<td><input type="hidden" placeholder={cnum} name="cnum" id="cnum" /> </td>
<button
onClick={(e) => {
e.preventDefault();
this.deleteById(_id);
}}
disabled={isLoading}
>
Delete
</button>
<button
onClick={(e) => {
e.preventDefault();
var siteLocation = document.getElementById('location').value
var Services = document.getElementById('Services').value
var cnum = document.getElementById('cnum').value
this.editById(_id, siteLocation, Services, cnum)
}}
>
Submit Edit
</button>
</tr>
))
: "No Data Found"}
</table>
);
}
}
const script = document. createElement("script"); $('input').keyup(function(){
if($.trim(this.value).length > 0)
$('#location').show()
else
$('#location').hide()
});
export default TourPage;
thanks 4 the help in advance.
You can use onfocus() in the text element. If you want to hide the button, use onfocusout() or in case if you want to track only after input has changed, use onchange() event
...
//class function
onTyping =()=>{
this.setState({
showSubmit:true
})
}
...
//render part
render(){
...
//input which you want to track typing
<input type="text" onfocus={()=>this.onTyping()} placeholder={location} name="location" id="location" />
...
//element submit button
{this.state.showSubmit && <button
onClick={(e) => {
e.preventDefault();
var siteLocation = document.getElementById('location').value
var Services = document.getElementById('Services').value
var cnum = document.getElementById('cnum').value
this.editById(_id, siteLocation, Services, cnum)
}}
>
Submit Edit
</button>}
...
Here is an example that helps you,
const {
useState
} = React;
const Test = () => {
const [show, setShow] = useState(false);
const handleChange = (event) => {
if (event.target.value.length > 0)
setShow(true);
else
setShow(false)
}
return ( <div>
<input type = "text"
onChange = {
(event) => handleChange(event)
}/>
{show && < button > Submit changes now! </button>}
</div>
)
}
ReactDOM.render( < Test / > ,
document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
There is a way to avoid jquery and continue using your react class component to achieve this.
Map over state.myData to render each item with an input and a button.
Use the array index with the input's onChange event callback to add the inputValue into the correct array item's object within state.
Use the array index with the button's onClick event callback to get the item from state.myData before sending it to the server.
If there is an inputValue for the item, you can conditionally render the button.
import React, { Component } from "react";
import axios from "axios";
class TourPage extends Component {
constructor(props) {
super(props);
this.state = {
myData: [],
isLoading: true
};
}
componentDidMount() {
axios
.get("https://rickandmortyapi.com/api/character")
.then((res) => {
this.setState({
myData: res.data.results
});
})
.finally(() => {
this.setState({
isLoading: false
});
});
}
handleChangeInput = ({ target }, index) => {
const newData = [...this.state.myData];
newData[index].inputValue = target.value;
this.setState({
myData: newData
});
};
handleSubmitEdit = (index) => {
const item = this.state.myData[index];
// submit the edit to the api
console.log(
`Clicked on 'submit edit' for ${item.name} with value ${item.inputValue}`
);
};
render() {
let { myData, isLoading } = this.state;
if (isLoading) {
return "loading...";
}
return (
<div>
{myData.map(({ name, status, species, inputValue }, index) => {
return (
<div key={index}>
<p>{`${name} - ${species} - ${status}`}</p>
<input
type="text"
onChange={(e) => this.handleChangeInput(e, index)}
value={inputValue || ""}
/>
{inputValue && (
<button onClick={() => this.handleSubmitEdit(index)}>
Submit Edit
</button>
)}
</div>
);
})}
</div>
);
}
}
export default TourPage;
If you wanted to have an input per field within each row, you could make some small changes and save your edits to the item's state within a nested object.
Then you could check if there was anything inside that row's edits object to conditionally show the submit button per row.
import React, { Component } from "react";
import axios from "axios";
import isEmpty from "lodash.isempty";
import pick from "lodash.pick";
class TourPage extends Component {
constructor(props) {
super(props);
this.state = {
myData: [],
isLoading: true
};
}
componentDidMount() {
axios
.get("https://rickandmortyapi.com/api/character")
.then((res) => {
this.setState({
// here we create an empty 'edits' object for each row
myData: res.data.results.map((d) => ({
...pick(d, ["name", "status", "species"]),
edits: {}
}))
});
})
.finally(() => {
this.setState({
isLoading: false
});
});
}
handleChangeInput = ({ target }, index) => {
const newData = [...this.state.myData];
const { value, name } = target;
newData[index].edits[name] = value;
this.setState({
myData: newData
});
};
handleSubmitEdit = (index) => {
const item = this.state.myData[index];
// submit the edit to the api
console.log(`Clicked on 'submit edit' for ${item.name} with edits:`);
console.log(item.edits);
console.log("Updated item: ");
const { edits, ...orig } = item;
const newItem = { ...orig, ...edits };
console.log(newItem);
// Once saved to api, we can update myData with newItem
// and reset edits
const newData = [...this.state.myData];
newData[index] = { ...newItem, edits: {} };
this.setState({
myData: newData
});
};
showButton = (index) => {
const { edits } = this.state.myData[index];
return !isEmpty(edits);
};
render() {
let { myData, isLoading } = this.state;
if (isLoading) {
return "loading...";
}
return (
<table>
<tbody>
{myData.map((row, index) => {
const { edits, ...restRow } = row;
return (
<tr key={index}>
{Object.keys(restRow).map((col) => {
return (
<td>
<label>
{col}:
<input
name={col}
value={edits[col] || restRow[col]}
onChange={(e) => this.handleChangeInput(e, index)}
/>
</label>
</td>
);
})}
<td>
{this.showButton(index) && (
<button onClick={() => this.handleSubmitEdit(index)}>
Submit Edit
</button>
)}
</td>
</tr>
);
})}
</tbody>
</table>
);
}
}
export default TourPage;

How can I make only one list item expand when a button is clicked in React (no hooks)?

I have a list of students and I want to make an expandable list view. Basically each student will have a plus & minus button and every time it's clicked a list of all student's grades will expand. However, so far when I click on one of the buttons it opens all the students' grade lists at the same time.
I can't seem to figure out how I can fix this so that when I click on a specific student it will open only that student's grades. Can anyone help me on this? I think I'm close, but I can't get there!
Here's my code:
import React from 'react';
import Average from './Average';
import './App.css';
class App extends React.Component{
state = {
students: [],
error: null,
search: null,
open: false,
}
componentDidMount(){
fetch('https://api.hatchways.io/assessment/students')
.then(res => res.json())
.then(
(data) => {
this.setState({
students: data.students,
})
},
(error) => {
this.setState({ error });
})
}
handleChange = (e) => {
this.setState({ search: e.target.value });
}
togglePanel = e => {
this.setState({ open: !this.state.open })
}
render(){
let { search, students, open } = this.state;
const display = students.filter((student) => {
if(search == null)
return student;
else if(student.firstName.toLowerCase().includes(search.toLowerCase()) ||
student.lastName.toLowerCase().includes(search.toLowerCase())){
return student;
}
}).map((student, idx) => {
return (
<div className = "student-container" key = {student.id}>
<img className = "student-pic" src = {student.pic} alt = "pictures"/>
<div className = "student-mini">
<h1>{student.firstName.toUpperCase()} {student.lastName.toUpperCase()}</h1>
<p>Email: {student.email}</p>
<p>Company: {student.company}</p>
<p>Skill: {student.skill}</p>
<Average grades = {student.grades}/>
<button onClick = {(e) => this.togglePanel(e)}>{open ? '-' : '+'}</button>
<div>
<p>{open ? student.grades.map((grade, id) => {
return (
<p key = {id}>Test {id + 1}: {grade}%</p>
)
}): null}
</p>
</div>
</div>
</div>
)
})
return (
<div className = "gray-container">
<div className = "white-container">
<form>
<input onChange = {this.handleChange} type = "text" placeholder = "Search by
name">
</input>
</form>
<div>
{display}
</div>
</div>
</div>
)
}
}
export default App;
Each of your expandable panels uses the same single open state to determine whether it should be expanded or not, that is why they all open at once. The easiest solution here is for each panel to have its own state.
Ideally, you want to extract the JSX from your map's return statement to separate component presenting a single student's panel, let's say StudentPanel, pass the student object as prop and move the open state and the toggle function to that component as well.
UPDATE: You'd have something like this:
class StudentPanel extends React.Component {
state = {
open: false
}
togglePanel = e => {
this.setState(prevState => ({ open: !prevState.open }))
}
render() {
const { student } = this.props;
return (
<div className = "student-container" key = {student.id}>
// (...) rest of JSX
</div>
);
}
}
In render of your App you'd have:
(...).map(student => <StudentPanel student={student} />)
and the open property and togglePanel can be removed from App component completely.

React ToDoList Project - Unique IDs

I am trying to introduce unique identifiers for list items instead of using the index but every method I try, I can't seem to get it working in the child. This is the base I am working with. I did install and imported import { v4 as uuidv4 } from 'uuid'; to make it a bit easier
All you have to do is simply put in 'uuidv4()' to generate a random ID
Parent
import React from 'react';
import './App.css';
import ShoppingCartList from './ShoppingCartList'
import { v4 as uuidv4 } from 'uuid';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
shoppingCart: [],
newItem: '',
errorMessage: 'false',
};
this.onRemoveItem = this.onRemoveItem.bind(this);
}
handleChange = (e) => {
this.setState ({ newItem: e.target.value})
}
handleClickAdd = (e) => {
if(this.state.newItem === '') {
this.setState({errorMessage: 'true'});
} else {
return ( this.setState({ shoppingCart: this.state.shoppingCart.concat(this.state.newItem) }),
this.setState({newItem: ''}),
this.setState({errorMessage: 'false'})
)}
}
handleSubmit = (e) => {
e.preventDefault()
}
onRemoveItem = (i) => {
this.setState(state => {
const shoppingCart = state.shoppingCart.filter((item, j) => i !== j);
return {shoppingCart}
})}
render() {
return (
<div>
<form onSubmit ={this.handleSubmit}>
Shopping Cart Items
<br></br>
{ this.state.errorMessage === 'true' &&
<p className='error'> Please enter an item </p> }
<ul>
{this.state.shoppingCart.map((item, index,) => {
return <ShoppingCartList
item={item}
index={index}
onRemoveItem={this.onRemoveItem}
/>
})}
</ul>
<input
placeholder='Enter your item here'
value={this.state.newItem}
onChange={this.handleChange}
></input>
<button type='submit' onClick={this.handleClickAdd}>Add to Shopping list</button>
</form>
</div>
)
}
}
export default App;
Child
[code]
import React from 'react';
function ShoppingCartList ({item,index, onRemoveItem}) {
return (
<li key={item}>{item} <button type="button" onClick={() => onRemoveItem(index)}>Delete</button></li>
)
}
export default ShoppingCartList;
Issues
React keys should be defined on the element/component being mapped, inside the child component is the wrong location
Solution
When adding items to the shopping cart, generate the unique id when adding to state.
Use the item id as the react key in the parent when mapping the cart
items, and as a way to identify the item to be removed from the cart.
Update handleClickAdd to create a new item object with id and value. Spread the existing cart array into a new array and append the new item object to the end.
handleClickAdd = (e) => {
if (this.state.newItem === "") {
this.setState({ errorMessage: true });
} else {
this.setState((prevState) => ({
shoppingCart: [
...prevState.shoppingCart,
{
id: uuidv4(), // <-- new unique id
value: prevState.newItem // <-- item value
}
],
newItem: "",
errorMessage: false
}));
}
};
Update onRemoveItem to take an id to filter by.
onRemoveItem = (id) => {
this.setState((prevState) => ({
shoppingCart: prevState.shoppingCart.filter((item) => item.id !== id)
}));
};
Update your render to add the react key to ShoppingCartList.
{this.state.shoppingCart.map((item) => {
return (
<ShoppingCartList
item={item}
key={item.id}
onRemoveItem={this.onRemoveItem}
/>
);
})}
Update ShoppingCartList to render the item value and pass the item id to the remove item callback.
const ShoppingCartList = ({ item, onRemoveItem }) => (
<li>
{item.value}{" "}
<button type="button" onClick={() => onRemoveItem(item.id)}>
Delete
</button>
</li>
);

React: How to send data on Popup close?

I have this Popup that I built in my React app. It's, in a sense, another page inside the Popup. In this Popup, there is a list. There are no forms at all in this Popup window. I only have another popup inside this popup with a submission form that adds another item to the list.
Therefore, what I'm attempting to do is to submit the list to the Parent component when I click on the "Close" button to close the Popup window. How do I do that?
Here's my code:
SingleBox.js
import React, { Component } from "react";
import SecurityForm from "../SecurityForm/index";
import PriceForm from "../PriceForm/index";
export default class SingleSecuritybox extends Component {
constructor(props) {
super(props);
this.state = {
showPopup: false,
showPricePopup: false, //don't show popup
pricelist: this.props.price
};
}
/* toggle and close popup edit form window */
togglePopup = () => {
this.setState(prevState => ({
showPopup: !prevState.showPopup
}));
};
togglePricePopup = () => {
this.setState(prevState => ({
showPricePopup: !prevState.showPricePopup
}));
};
/* handles edit current security form submissions */
handleEditSecuritySubmission = editSecurity => {
const { editCurrentSecurity, id } = this.props;
this.togglePopup();
editCurrentSecurity({ ...editSecurity, id });
};
updatePrice = updatePrice => {
const { updatePriceList, id } = this.props;
this.togglePricePopup();
updatePriceList({...updatePrice, id});
console.log("editing price", updatePrice);
};
/* handles delete current security form submissions */
handleDeleteSecurity = () => {
const { deleteSecurity, id } = this.props;
// toggle the pop up (close)
this.togglePopup();
// sends the id back to App's "this.deleteSecurity"
deleteSecurity(id);
};
render() {
return (
<div className="box">
<article className="securitytable">
<div className="title">
<h2>
<strong>{this.props.name}</strong>
</h2>
<hr className="lightgray-line" />
</div>
<table>
<tbody>
<tr>
<td className="isin-width">{this.props.isin}</td>
<td className="country-width">{this.props.country}</td>
<td>
<button type="button" className="price-btn" onClick={this.togglePricePopup}>Prices</button>
{this.state.showPricePopup ? (
<PriceForm
pricelist= {this.props.price}
updatePrice={ this.updatePrice }
addPrice={this.props.addPrice}
closePopup= {this.togglePricePopup}
/>
) : null}
</td>
<td className="editing-btn">
<button
type="button"
className="edit-btn"
onClick={this.togglePopup}
>
Edit
</button>
{this.state.showPopup ? (
<SecurityForm
{...this.props}
handleEditSecuritySubmission={ this.handleEditSecuritySubmission }
handleDeleteSecurity={this.handleDeleteSecurity}
cancelPopup={this.togglePopup}
/>
) : null}
</td>
</tr>
</tbody>
</table>
</article>
</div>
);
}
}
This code in question is this list that'll open in Popup window which is a child componenet:
<button type="button" className="price-btn" onClick={this.togglePricePopup}>Prices</button>
{this.state.showPricePopup ? (
<PriceForm
pricelist= {this.props.price}
updatePrice={ this.updatePrice }
addPrice={this.props.addPrice}
closePopup= {this.togglePricePopup}
/>
) : null}
In this child component, which is Price Popup:
import React, { Component } from "react";
import PriceBox from "../SinglePricebox/index";
import AddPriceForm from "../AddPriceForm/index";
export default class PriceForm extends Component {
constructor(props) {
super(props);
this.state = {
priceArr: this.props.pricelist,
showPricePopup: false,
addPricePopup: false,
isToggleOn: true,
date: props.date || "",
number: props.number || ""
};
}
updateInput = ({ target: { name, value } }) =>
this.setState({ [name]: value });
togglePopup = () => {
this.setState(prevState => ({
showPopup: !prevState.showPopup
}));
};
togglePricePopup = () => {
this.setState(prevState => ({
showPricePopup: !prevState.showPricePopup
}));
};
addPricePopup = () => {
this.setState(prevState => ({
addPricePopup: !prevState.addPricePopup
}));
};
/* adds a new price to the list */
addPrice = newPrice => {
this.setState(prevState => ({
addPricePopup: !prevState.addPricePopup,
// spreads out the previous list and adds the new price with a unique id
priceArr: [...prevState.priceArr, { ...newPrice }]
}));
};
handleListSubmit = () => {
const { priceArr } = this.state;
const { updatePrice } = this.props;
const fields = {priceArr};
this.setState(() => {
// if (addPrice) addPrice(fields);
updatePrice(fields);
});
console.log("submission", fields);
};
render() {
return (
<div className="popup">
<div className="popup-inner">
<div className="price-form">
<h2>Prices</h2>
<div className="scroll-box">
{this.state.priceArr.map((props) => (
<PriceBox
{...props}
key={props.date}
/>
))}
</div>
<div className="buttons-box flex-content-between">
<button
type="button"
onClick={this.addPricePopup}
className="btn add-button">Add +</button>
{this.state.addPricePopup && (
<AddPriceForm
addPrice={this.addPrice}
cancelPopup={this.addPricePopup}
/>
)}
<div className="add-btns">
<button
type="button"
onClick={this.handleListSubmit}
className="btn cancel-button"
>
Close
</button>
</div>
</div>
</div>
</div>
</div>
);
}
}
What I'm attempting to do is to send the data (the list array) back to the Parent component on close, but I notice that I can send the data back but I couldn't close the window...
<button
type="button"
onClick={this.handleListSubmit}
className="btn cancel-button"
>
Close
</button>
How do I do this? I cannot add something like this.props.closePopup(); in the handleListSubmit function because while it can close the window, it prevents the list array from being submitted and passed to the Parent component.
You can use parent callback function to send data from child to parent.
on child
handleListSubmit = () => {
...
this.props.onSummited(data)
}

Toggle switch button not working in reactJs app

I want a container with table that has one column "enabled" which can be toggled. I want to save the state of toggle in object I used to display the row (In the example below, I want to store it in enable attribute of student object). I have table and toggle button displaying properly. But the toggle button is not clickable/togglable and doesnt store the state. live code here.
Here is my code
class student {
constructor(id, name, age,email,enable) {
this.id = id;
this.name = name;
this.age = age;
this.email = email;
this.enable = enable;
}
}
const Switch = ({ isOn, handleToggle}) => {
return (
<>
<input
checked={isOn}
onChange={handleToggle}
className="react-switch-checkbox"
id={`react-switch-new`}
type="checkbox"
/>
<label
className="react-switch-label"
htmlFor={`react-switch-new`}
>
<span className={`react-switch-button`} />
</label>
</>
);
};
class Table extends React.Component {
constructor(props) {
super(props)
this.state = {
students: [ new student(1, 'foo', 12, 'foo#gmail.com', true),
new student(2, 'bar', 22, 'bar#gmail.com', false),
new student(3, 'foobar', 44, 'foo#gmail.com', true),
new student(4, 'foofoo',57, 'foofoo#gmail.com', false)
]
}
}
renderTableHeader() {
let header = Object.keys(this.state.students[0])
return header.map((key, index) => {
return <th key={index}>{key.toUpperCase()}</th>
})
}
renderTableData() {
return this.state.students.map((student, index) => {
const { id, name, age, email, enable } = student //destructuring
//const [value, setValue] = useState(false);
return (
<tr key={id}>
<td>{id}</td>
<td>{name}</td>
<td>{age}</td>
<td>{email}</td>
<td><Switch
isOn={enable}
handleToggle={() => student.enable=!enable}
/></td>
</tr>
)
})
}
render() {
return (
<div>
<h1 id='title'>React Dynamic Table</h1>
<table id='students'>
<tbody>
<tr>{this.renderTableHeader()}</tr>
{this.renderTableData()}
</tbody>
</table>
</div>
)
}
}
ReactDOM.render(<Table />, document.getElementById('root'));
Here is the screenshot of how page looks
The issue is, you cannot directly change the state like,
handleToggle={() => student.enable=!enable}
This will never change your state. To change your state you must use setState.
You should have a dedicated function to toggle your state,
handleToggle = (id) => {
this.setState({
students: this.state.students.map(std => {
if(parseInt(std.id) === parseInt(id)){ //parse id to integer for safer side
return {...std, enable: !std.enable}
}else{
return std;
}
})
})
}
You should provide this function to your Switch. Also provide id for updation.
<Switch
isOn={enable}
id={id} //provide id for updation
handleToggle={this.handleToggle} //provide function reference
/>
You need to make some changes to your Switch,
const Switch = ({ isOn, handleToggle, id}) => { //take prop id
return (
<>
<input
checked={isOn}
onChange={() => handleToggle(id)} //call handleToggle using id
className="react-switch-checkbox"
id={`react-switch-new${id}`} // Make it unique by adding id
type="checkbox"
/>
<label
className="react-switch-label"
htmlFor={`react-switch-new${id}`} // Make it unique by adding id
>
<span className={`react-switch-button`} />
</label>
</>
);
};
Demo

Categories

Resources