I did a CRUD (UI only) simple component in react, but how do I make the primary contact to be the first one in my table? The app can do crud, check and uncheck primary contact, only one primary contact is allowed in the table.
Working demo
https://codesandbox.io/s/r7kmp9rkom
================================================
I've tried using lodash's sortBy
(Broken demo using sortBy
https://codesandbox.io/s/pjj3098lmx)
line 130
<tbody>
{sortBy(contacts, o => !o.primary).map((o, i) => {
return (
<tr className={classNames({ primary: o.primary })} key={i}>
<td>{o.name}</td>
<td>{o.email}</td>
<td>
<button
onClick={() =>
this.setState({
openModal: true,
modalAction: "update",
selected_contact: o,
selected_contact_index: i
})
}
>
Edit
</button>
</td>
</tr>
);
})}
</tbody>
But it broke the functionality. I think it has to do with the index problem.
I couldn't solve it I don't know why sortBy doesn't retain the index. Another silly option would be using flexbox order but I hope I could solve it using just javascript.
As you told it is an index problem
I have used lodash's uniqueId method to retain id value, never use an index as key for a dynamic list when we have operations like deleting/updating/adding.
if an app is a server-side render id must come from a backend.
id: uniqueId("contact_")
Working Demo link
static defaultProps = {
data: {
contacts: [
{
name: "James",
email: "james#havard.edu",
primary: false,
id: uniqueId("contact_")
},
{
name: "Mark",
email: "mark#standford.edu",
primary: true,
id: uniqueId("contact_")
}
]
}
};
onSaveContact = (action, newContact, newContact_index) => {
if (action === "add") {
if (newContact.primary) {
const setNonePrimary = this.state.contacts.map(o => ({
...o,
primary: false
}));
this.setState({
contacts: [
...setNonePrimary,
{ ...newContact, id: uniqueId("contact_") }
]
});
} else {
this.setState({
contacts: [
...this.state.contacts,
{ ...newContact, id: uniqueId("contact_") }
]
});
}
} else if (action === "update") {
this.setState({
contacts: [
...this.state.contacts.map((o, i) => {
if (o.id === newContact_index) {
return { ...newContact };
} else {
if (newContact.primary) {
return { ...o, primary: false };
} else {
return { ...o };
}
}
})
]
});
} else if (action === "delete") {
this.setState({
contacts: [
...this.state.contacts.filter((o, i) => {
if (o.id !== newContact_index) {
return o;
}
})
]
});
}
Related
I need to set the active classname to multiple onclick items inside a .map
I need the list of active items that were clicked
The items that were clicked will be highlighted in yellow, and when i click the same item again it should be removed from active list items.
const [data, setData] = useState([]);
const [activeIndicies, setActiveIndicies] = useState(() =>
data?.map(() => false)
);
useEffect(() => {
// This data is coming from the API response
const data = [
{ id: 1, name: "one" },
{ id: 2, name: "two" },
{ id: 3, name: "three" }
];
setData(data);
}, []);
return statement
onClick={() => {
setActiveIndicies(
activeIndicies.map((bool, j) => (j === index ? true : bool))
);
}}
Code Sandbox
Thank you.
try this one:
import "./styles.css";
import React, { useState, useEffect } from "react";
export default function App() {
const [data, setData] = useState([
{ id: 1, name: "one", active: false },
{ id: 2, name: "two", active: false },
{ id: 3, name: "three", active: false }
]);
return (
<div className="App">
<h2>Set active className to multiple items on .map</h2>
{data?.map((item, index) => {
return (
<p className={data[index].active ? "selected" : "notselected"}
onClick={() => {
setData((prevState) =>
_.orderBy(
[
...prevState.filter((row) => row.id !== item.id),
{ ...item, active: !item.active }
],
["name"],
["asc"]
)
);
}}
>
{item.name}
</p>
);
})}
</div>
);
}
You can acheive this by simply making some minor changes to your code:
// Changing the state value to an object so that it can
// store the active value for exact item ids
const [activeIndicies, setActiveIndicies] = useState({});
Then inside of .map()
....
// Checking if there is any value for the item id which is being mapped right now.
const selected = activeIndicies[item.id];
return (
<p
className={selected ? "selected" : "notselected"}
onClick={() => {
/* Then setting the state like below where it toggles
the value for particular item id. This way if item is
selected it will be deselected and vice-versa.
*/
setActiveIndicies((prevState) => {
const newStateValue = !prevState[item.id];
return { ...prevState, [item.id]: newStateValue };
});
}}
// Key is important :)
key={item.id}
>
{item.name}
</p>
);
Hello, friends!
I solved this problem in a more convenient way for me )
const data = [
{ id: 1, name: "Ann", selected: true },
{ id: 2, name: "Serg", selected: false },
{ id: 3, name: "Boris", selected: true },
];
//you don't even need to have a boolean field in the object -
//it will be added by itself on the first click on the element
// const data = [{ name:"Ann", id:1}, { name:"Serg", id:2 },{ name:"Boris", id:3 },]
const [users, setUsers] = useState(data); // no square brackets-[data]
function handleActive(item) {
setUsers((prev) => {
return prev.map((itemName) => {
if (itemName.name === item.name) {
return { ...itemName, selected: !itemName.selected };
// itemName.selected = !itemName.selected // or so
}
return itemName;
});
});
}
return (
{
users.map((item, i) => {
// let current = item.selected === true
// or so -> className={current === true ? 'users': ''}
return (
<div
onClick={() => handleActive(item)}
className={item.selected === true ? "active" : ""}
key={i}
>
{item.name}
</div>
);
})
}
);
I am using react-bootstrap-table2 to make HTML tables, I am using a checkbox inside my table to delete the items.
SO as per This link, it is mentioned how to get the selected row and then do the next part, here what I am doing is when I click on any checkbox row gets selected, and if I again select any row that I am adding to the array into my state like below
onSelect: (row, isSelect, rowIndex, e) => {
if (isSelect === true) {
setrowData((rowData) => [...rowData, row]);
} else {
// here i need to do something
}
},
My issue is when I unselect the row that value is not getting deleted from my array, and at the time of delete, I have all the data which I have selected once.
One more thing which is related to this is when I check any row I want to show delete button and when none of the rows is checked I want to hide the delete button, here select is giving me the boolean value for that, but it is working for each select once I am selecting multiple rows it shows up, but when I unselect any one of them the delete button hides
What I have done for that is something like below
setrowSelect((rowSelect) => [...rowSelect, isSelect]); // this one is inside onSelect callback given by the react-bootstrap-table2 library
{rowSelect && (
<button className="btn Secondary_Button_with_Icon">
<i className="ri-upload-cloud-line ri-lg"></i>Register
</button>
)}
My full working code
Use a filter method inside your else block to remove that unselected element from the array
onSelect: (row, isSelect, rowIndex, e) => {
if (isSelect === true) {
setrowData((rowData) => [...rowData, row]);
} else {
setrowData((rowData) => rowData.filter((x,i)=>i!==rowIndex))
}
setrowSelect((rowSelect) => [...rowSelect, isSelect]);
},
Note that, you don't need to maintain another state for controlling visibility of Delete button.
You can perfectly hide/show Delete based on rowData state.
Also the code you wrote for handling selected rows works perfectly well. Just get rid of rowSelect state and its handlers.
And update the rendering of your Delete button based on contents of your rowData as:
{
rowData.length ? (
<button className="btn btn-primary" onClick={Delete_device}>
<i className="ri-upload-cloud-line ri-lg"></i>Delete
</button>
)
: null
}
This is the forked sandbox from yours.
try to change onSelect function like this
onSelect: (row, isSelect, rowIndex, e) => {
if (isSelect === true) {
setrowData((rowData) => [...rowData, row]);
rowSelect.push(true);
setrowSelect(rowSelect);
} else {
setrowData((rowData) => rowData.filter((x, i) => i !== rowIndex));
rowSelect.pop();
setrowSelect(rowSelect);
}
}
Here is one way to implement what you want :
1.Keep your data in one object, and add an id and isSelect fields
const data = [
{
id: "id-1",
fname: "john",
lname: "smith",
isSelect: false
},
{
id: "id-2",
fname: "steve",
lname: "warn",
isSelect: false
},
{
id: "id-3",
fname: "michel",
lname: "clark",
isSelect: false
}
];
2.pass this data to useState :
const [rowData, setrowData] = useState(data);
3.onSelect : just find the row by id and set isSelect field
onSelect: (row, isSelect, rowIndex, e) => {
setrowData((rows) => {
return rows.map((r) => {
if (r.id !== row.id) {
return r;
}
return { ...r, isSelect };
});
});
},
4.onSelectAll set isSelect on all rows
onSelectAll: (isSelect, rows, e) => {
setrowData((rows) => {
return rows.map((row) => {
return { ...row, isSelect };
});
});
}
5.for Delete_device just filter the data that is not selected :
const Delete_device = () => {
setrowData((rows) => {
return rows.filter((row) => !row.isSelect);
});
};
6.for the delete button, get the selected rows and count them, if the count is > 0 then show the button :
const selectedRows = rowData.filter((row) => row.isSelect);
return (
<div className="App">
{selectedRows.length > 0 && (
<button className="btn btn-primary" onClick={Delete_device}>
<i className="ri-upload-cloud-line ri-lg"></i>Delete
</button>
)}
7.Pass the state data to BootstrapTable
<BootstrapTable
bootstrap4
keyField="fname"
data={rowData}
columns={tableData[0].columnsData}
selectRow={selectRow}
/>
Complete example
I updated your state to use your data and removed the select array from your select logic. I also optimized it a bit. Its minor change from your codesandbox sample. Also, I recommend you use ids.
import React, { useState, useMemo } from "react";
import "./styles.css";
import "bootstrap/dist/css/bootstrap.min.css";
import BootstrapTable from "react-bootstrap-table-next";
import "react-bootstrap-table-next/dist/react-bootstrap-table2.min.css";
let tableData = [
{
rowsData: [
{
fname: "john",
lname: "smith"
},
{
fname: "steve",
lname: "warn"
},
{
fname: "michel",
lname: "clark"
}
],
columnsData: [
{
dataField: "fname",
text: "First name",
sort: true
},
{
dataField: "lname",
text: "last Name",
sort: true
}
]
}
];
export default function App() {
const [rowData, setrowData] = useState(tableData[0].rowsData);
const [rowSelect, setrowSelect] = useState([]);
const selectRow = useMemo(
() => ({
mode: "checkbox",
clickToSelect: false,
classes: "selection-row",
onSelect: (row, isSelect, rowIndex, e) => {
setrowSelect((rowData) =>
isSelect
? [...rowData, row]
: rowData.filter(
({ fname, lname }) => row.fname !== fname && row.lname !== lname
)
);
// if (isSelect === true) {
// setrowSelect((rowData) => [...rowData, row]);
// } else {
// console.log("onSelect", rowIndex, row, isSelect);
// setrowSelect((rowData) =>
// rowData.filter(
// ({ fname, lname }) => row.fname !== fname && row.lname !== lname
// )
// );
// }
},
onSelectAll: (isSelect, rows, e) => {
if (isSelect === true) {
setrowSelect(rows);
} else setrowSelect([]);
}
}),
[]
);
const Delete_device = () => {
console.log("Delete device", rowData, rowSelect);
if (rowSelect.length < 1) return;
setrowData((data) =>
data.filter(
({ fname, lname }) =>
rowSelect.find((s) => s.fname === fname && s.lname === lname) == null
)
);
setrowSelect([]);
};
console.log("App", rowData, rowSelect);
return (
<div className="App">
{rowData.length > 0 && (
<button className="btn btn-primary" onClick={Delete_device}>
<i className="ri-upload-cloud-line ri-lg"></i>Delete
</button>
)}
<BootstrapTable
bootstrap4
keyField="fname"
data={rowData}
columns={tableData[0].columnsData}
selectRow={selectRow}
/>
</div>
);
}
https://codesandbox.io/s/react-bootstrap-table-x-wus5r?file=/src/App.js
I want to update state array object by particular id.
Suppose I have following object in state. And I tried to update by following way using id but, it doesn't work for me.
It didn't update state data.
this.state = {
data: [{id:'124',name:'qqq'},
{id:'589',name:'www'},
{id:'45',name:'eee'},
{id:'567',name:'rrr'}]
}
publishCurrentProject = user => {
this.setState(prevState => ({
data: prevState.data.map(item =>
item.id === user.id ? { ...user } : item
),
}))
}
let user = {id:'124',name:'ttt'};
publishCurrentProject(user);
Any help would be greatly appreciated.
Maybe the problem is on how you called the publishCurrentProject(), maybe you put that function in the wrong context. I use your implementation and it still works
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [
{ id: "124", name: "qqq" },
{ id: "589", name: "www" },
{ id: "45", name: "eee" },
{ id: "567", name: "rrr" }
]
};
this.handleClick = this.handleClick.bind(this);
this.publishCurrentProject = this.publishCurrentProject.bind(this);
}
handleClick(e) {
let user = { id: "124", name: "ttt" };
this.publishCurrentProject(user);
}
publishCurrentProject(user) {
this.setState((prevState) => ({
data: prevState.data.map((item) =>
item.id === user.id ? { ...user } : item
)
}));
}
render() {
return (
<div className="App">
<h1>Test</h1>
{this.state.data.map((el) => (
<p>{el.name}</p>
))}
<button onClick={this.handleClick}>Change</button>
</div>
);
}
}
Codesandbox for worked example
I'm having an issue where upon loading the page I can either sort the table by the "name" column (ascending or descending) - - OR - - use a searchbar to filter through the names of the employees. My issue is that once I've sorted alphabetically, the search/filter no longer works.
I'm very new to React (I'm sure that's very obvious by my code) so please let me know if there's something obvious I'm doing wrong. Thanks in advance!
import React, { Component } from "react";
import API from "../utils/API"
import EmployeeRow from "./EmployeeRow"
class TableMain extends Component {
state = {
result: [],
search: "",
sortOrder: "descending"
}
componentDidMount() {
API.search()
.then(results => {
console.log(results)
this.setState({
result: results.data.results.map((res, i) => ({
image: res.picture.large,
firstName: res.name.first,
lastName: res.name.last,
phone: res.phone,
email: res.email,
dob: res.dob.date,
key: i
})
)
})
})
};
filterResults = (results) => {
const value = this.state.search
const finalResult = results.filter((employee) => {
const lastName = employee.lastName.toLowerCase();
const firstName = employee.firstName.toLowerCase()
const fullName = firstName + " " + lastName
if (fullName.includes(value)) {
return employee
}
});
return finalResult
};
sortResults = (event) => {
const results = this.state.result
// const id = event.target.id
// if (id === 'name'){
// } else if (id === 'phone'){
// } else if (id === 'email'){
// }
if (this.state.sortOrder === "descending") {
results.sort((a, b) => {
if (a.firstName > b.firstName) {
return -1
}
return a.firstName > b.firstName ? 1 : 0
},
this.setState({ sortOrder: "ascending" }))
} else if (this.state.sortOrder === "ascending") {
results.sort((a, b) => {
if (a.firstName < b.firstName) {
return -1
}
return a.firstName > b.firstName ? 1 : 0
},
this.setState({ sortOrder: "descending" }))
}
console.log("RESULTS: ", results)
this.setState({
sortedResults: results,
isSorted: true
})
}
onChange = e => {
const value = e.target.value;
if (!value) {
this.setState({ isSearchEmpty: true });
} else {
this.setState({ search: e.target.value, isSearchEmpty: false });
}
}
render() {
// console.log("State", this.state)
let employeeResults = this.state.result
if (this.state.isSearchEmpty) {
employeeResults = this.state.result
} else {
employeeResults = this.filterResults(this.state.result)
}
if (this.state.isSorted) {
employeeResults = this.state.sortedResults
}
return (
<div>
<input label="Search" onChange={this.onChange} />
<div className="row">
<table style={{ width: "100%" }}>
<tbody>
<tr>
<th>Image</th>
<th style={{ cursor: "pointer" }} onClick={this.sortResults} id="name">Name</th>
<th id="phone">Phone</th>
<th id="email">Email</th>
<th id="dob">DOB</th>
</tr>
{[...employeeResults].map((item) =>
<EmployeeRow
image={item.image}
firstName={item.firstName}
lastName={item.lastName}
email={item.email}
phone={item.phone}
dob={item.dob}
key={item.key}
/>
)}
</tbody>
</table>
</div>
</div>
)}
}
export default TableMain;
The issue is:
if (this.state.isSorted) {
employeeResults = this.state.sortedResults;
}
When you sort, you set state.isSorted to true, however you never set it back to false once you have finished. When you then try to filter, you do the filter:
if (this.state.isSearchEmpty) {
employeeResults = this.state.result;
} else {
employeeResults = this.filterResults(this.state.result);
}
if (this.state.isSorted) { // this is never reset after sorting.
employeeResults = this.state.sortedResults;
}
But as this.state.isSorted is still true, you use the values in this.state.sortedResults again.
please let me know if there's something obvious I'm doing wrong
You are making this tricky for yourself, as you are filtering/sorting the same collection of data. That's why you need to perform the action in the render, as you are trying to maintain the original list for later usage.
If you seperate the list into two collections: original unmodified and a display list, you can always refer to the original list to perform filtering/sorting.
componentDidMount() {
API.search().then(results => {
const tableData = results.data.results.map((res, i) => ({
image: res.picture.large,
firstName: res.name.first,
lastName: res.name.last,
phone: res.phone,
email: res.email,
dob: res.dob.date,
key: i
}));
this.setState({ originalResults: tableData, displayResults: tableData });
});
}
Then filtering can be done, as soon as the onChange occurs:
onChange = e => {
const query = e.target.value;
this.setState(prevState => ({
displayResults:
query.length > 0
? this.filterResults(query, prevState.originalResults)
: prevState.originalResults
}));
};
and similarly for the sorting, which can be performed on the display-results rather than the whole which means you can now sort, filtered results.
I created an example here https://codesandbox.io/s/sad-cannon-d61z6
I stubbed out all the missing functionality.
I have a state object that contains an array of objects:
this.state = {
feeling: [
{ name: 'alert', status: false },
{ name: 'calm', status: false },
{ name: 'creative', status: false },
{ name: 'productive', status: false },
{ name: 'relaxed', status: false },
{ name: 'sleepy', status: false },
{ name: 'uplifted', status: false }
]
}
I want to toggle the boolean status from true to false on click event. I built this function as a click handler but it doesn't connect the event into the state change:
buttonToggle = (event) => {
event.persist();
const value = !event.target.value
this.setState( prevState => ({
status: !prevState.status
}))
}
I'm having a hard time following the control flow of the nested React state change, and how the active event makes the jump from the handler to the state object and vice versa.
The whole component:
export default class StatePractice extends React.Component {
constructor() {
super();
this.state = {
feeling: [
{ name: 'alert', status: false },
{ name: 'calm', status: false },
{ name: 'creative', status: false },
{ name: 'productive', status: false },
{ name: 'relaxed', status: false },
{ name: 'sleepy', status: false },
{ name: 'uplifted', status: false }
]
}
}
buttonToggle = (event) => {
event.persist();
const value = !event.target.value
this.setState( prevState => ({
status: !prevState.status
}))
}
render() {
return (
<div>
{ this.state.feeling.map(
(stateObj, index) => {
return <button
key={ index }
onClick={ this.buttonToggle }
value={ stateObj.status } >
{ stateObj.status.toString() }
</button>
}
)
}
</div>
)
}
}
In order to solve your problem, you should first send the index of the element that is going to be modified to your toggle function :
onClick = {this.buttonToggle(index)}
Then tweak the function to receive both the index and the event.
Now, to modify your state array, copy it, change the value you are looking for, and put it back in your state :
buttonToggle = index => event => {
event.persist();
const feeling = [...this.state.feeling]; //Copy your array
feeling[index] = !feeling[index];
this.setState({ feeling });
}
You can also use slice to copy your array, or even directly send a mapped array where only one value is changed.
Updating a nested object in a react state object is tricky. You have to get the entire object from the state in a temporary variable, update the value within that variable and then replace the state with the updated variable.
To do that, your buttonToggle function needs to know which button was pressed.
return <button
key={ index }
onClick={ (event) => this.buttonToggle(event, stateObj.name) }
value={ stateObj.status } >
{ stateObj.status.toString() }
</button>
And your buttonToggle function could look like this
buttonToggle = (event, name) => {
event.persist();
let { feeling } = this.state;
let newFeeling = [];
for (let index in feeling) {
let feel = feeling[index];
if (feel.name == name) {
feel = {name: feel.name, status: !feel.status};
}
newFeeling.push(feel);
}
this.setState({
feeling: newFeeling,
});
}
Here's a working JSFiddle.
Alternatively, if you don't need to store any more data per feeling than "name" and "status", you could rewrite your component state like this:
feeling: {
alert: false,
calm: false,
creative: false,
etc...
}
And buttonToggle:
buttonToggle = (event, name) => {
event.persist();
let { feeling } = this.state;
feeling[name] = !feeling[name];
this.setState({
feeling
});
}
I think you need to update the whole array when get the event. And it is better to not mutate the existing state. I would recommend the following code
export default class StatePractice extends React.Component {
constructor() {
super();
this.state = {
feeling: [
{ name: "alert", status: false },
{ name: "calm", status: false },
{ name: "creative", status: false },
{ name: "productive", status: false },
{ name: "relaxed", status: false },
{ name: "sleepy", status: false },
{ name: "uplifted", status: false },
],
};
}
buttonToggle = (index, value) => (event) => {
event.persist();
const toUpdate = { ...this.state.feeling[index], status: !value };
const feeling = [...this.state.feeling];
feeling.splice(index, 1, toUpdate);
this.setState({
feeling,
});
};
render() {
return (
<div>
{this.state.feeling.map((stateObj, index) => {
return (
<button
key={index}
onClick={this.buttonToggle(index, stateObj.status)}
value={stateObj.status}
>
{stateObj.status.toString()}
</button>
);
})}
</div>
);
}
}