I am new to react so bear any nontechnical words.
I have parent component that displays the table headers, now next is child component which has tables' td along with one td is add button when the user clicks on add button. The similar child component should be added as a sibling to previous child component and this process should go on.
Child Component:
class ChildComp extends React.Component{
state = {
Avalue: {value: ''},
Bvalue: {value: ''},
Cvalue: {value: ''},
Dvalue: {value: ''},
Evalue: {value: ''},
Fvalue: {value: ''},
Gvalue: {value: ''},
}
AddanotherSimilarChildcomp=(e)=>{
e.preventDefault();
const historyData = {
A: this.state.A.value,
B:this.state.B.value,
C: this.state.C.value,
D: this.state.D.value,
E: this.state.E.value,
F: this.state.F.value,
G: this.state.G.value,
}
console.log(historyData);
//and should render another similar ChildComp component below the one in which the current ChildComp is present
}
handleChange=(e)=>{
e.preventDefault();
const target = e.target;
const inputName = target.name;
const inputValue = target.value;
this.setState({
[inputName] : {
value: inputValue,
}
});
}
render(){
return(
<tbody id="first-table-row">
<tr>
<td data-th="A"><input type="text" minmax="40" name="A" value={this.state.a.value} onChange={this.handleChange} /></td>
<td data-th="B"><input type="date" minmax="40" name="B" value={this.state.B.value} onChange={this.handleChange} /></td>
<td data-th="C"><input type="text" minmax="225" name="C" value={this.state.C.value} onChange={this.handleChange} /></td>
<td data-th="D"><input type="text" minmax="40" name="D"value={this.state.D.value} onChange={this.handleChange} /></td>
<td data-th="E"><input type="text" minmax="40" name="E" value={this.state.E.value} onChange={this.handleChange} /></td>
<td data-th="F"><input type="text" minmax="40" name="F" value={this.state.F.value} onChange={this.handleChange} /></td>
<td data-th="G">
<div id="samerow">
<span>{this.props.somedata}</span>
<input type="text" minmax="40" name="G"value={this.state.G.value} onChange={this.handleChange} />
</div>
</td>
<td className="save" ><button id="save-btn" onClick={this.AddanotherSimilarChildcomp} type='button'>Add</button></td>
</tr>
</tbody>
)
}
}
Parent Component:
class ParentComponent extends React.PureComponent{
render(){
return(
<div className='table-center' id='table1'>
<table className="rwd-table" id="tblBlah" >
<tbody>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>E</th>
<th>F</th>
<th>G</th>
<th> </th>
</tr>
</tbody>
<ChildComp/>
</table>
</div>
)
}
}
It sounds like you want to clone rows after the button is clicked.. Let me know if this is what you are looking for..
Hope this helps!
class ParentComponent extends React.Component {
render() {
return (
<div>
<table>
<tbody>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>E</th>
<th>F</th>
<th>G</th>
<th> </th>
</tr>
</tbody>
<ChildComp
rows={[
[1, 2, 3, 4, 5, 6, 7],
[8, 9, 10, 11, 12, 13, 14],
[14, 15, 16, 17, 18, 19, 20]
]}
/>
</table>
</div>
);
}
}
class ChildComp extends React.Component {
state = {
tableRows: []
};
componentDidMount() {
this.setState({ tableRows: this.props.rows });
}
addNewRow = (rowToClone, index) => event => {
let newRows = [...this.state.tableRows];
newRows.splice(index, 0, rowToClone.map(i => `${i}` + `${i[0] || i}`));
this.setState({ tableRows: newRows });
};
render() {
return (
<tbody>
{this.state.tableRows.map((row, index) => {
return (
<tr>
{row.map(i => <td>{i}</td>)}
<td>
<button onClick={this.addNewRow(row, index + 1)}>
Clone Row
</button>
</td>
</tr>
);
})}
</tbody>
);
}
}
ReactDOM.render(<ParentComponent />, document.body);
table, th, tr, td {
border: 1px solid black;
}
table {
border-collapse: collapse;
}
td {
width: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script>
I think you are over-complicating the logic for your component-tree. This is how I interpreted your question.
You have a Parent component that renders a table with headers.
Each Child component is a table row.
You have a button that should add more rows (Child components).
The table cells belonging to each row should be editable (hence
inputs).
See working sandbox: https://codesandbox.io/s/inspiring-wave-bpv7f
It makes the most sense to have the Parent component manage the data-set. So all logic that involves updating or adding something from the data-set should belong to the Parent, not the Child components.
Consider an example like this;
Parent.js
class App extends React.Component {
state = {
headers: ["name", "age", "job", "salary"],
data: [
[
{ name: "Bobby Hill", editting: false },
{ age: 13, editting: false },
{ job: "student", editting: false },
{ salary: 0, editting: false }
]
]
};
createHeaders = () => {
const { headers } = this.state;
return headers.map(item => <th className="table-header">{item}</th>);
};
createBody = () => {
const { data } = this.state;
return data.map((row, index) => (
<Child data={row} rowIndex={index} toggleEdit={this.toggleEdit} />
));
};
addRow = () => {
const { data } = this.state;
const rowTemplate = [
{ name: "", editting: true },
{ age: "", editting: true },
{ job: "", editting: true },
{ salary: "", editting: true }
];
this.setState({
data: [...data, rowTemplate]
});
};
toggleEdit = (rowIndex, cellIndex) => {
const dataCopy = [...this.state.data];
const itemToUpdate = dataCopy[rowIndex][cellIndex];
itemToUpdate.editting = !itemToUpdate.editting;
this.setState({
data: dataCopy
});
};
render() {
return (
<div className="table-center" id="table1">
<table className="rwd-table" id="tblBlah">
<tbody>
<tr>{this.createHeaders()}</tr>
{this.createBody()}
</tbody>
</table>
<button onClick={this.addRow}>Add Row</button>
</div>
);
}
}
In the Parent component we have:
A data-set in our state which is an array of arrays. Each array
pertains to table-row.
When we iterate over the data-set, we pass in an array to each Child
component, which will render the row.
The addRow function will add a new array to our data-set,
containing objects corresponding to each table-header/property.
The toggleEdit function helps us swap between edit modes for each
cell.
Child.js
import React from "react";
const Child = ({ data, rowIndex, toggleEdit }) => {
return (
<tr>
{data.map((cell, cellIndex) => (
<td
className="table-cell"
onDoubleClick={() => toggleEdit(rowIndex, cellIndex)}
>
{cell.editting ? (
<input value={Object.values(cell)[0]} />
) : (
<span>{Object.values(cell)[0]}</span>
)}
</td>
))}
</tr>
);
};
export default Child;
Now in the Child component:
It consumes the data (array) that was passed to it was a prop and
uses it to render the row.
For each item (object) in the array, it creates a table-cell to
display the value.
Double-clicking the cell will toggle the edit property of the item belonging to the parent-state.
If editting is true, than an input is displayed, if not just a
normal table-cell.
Related
I created a react js app and have a table and it contains a button "Add Available Day" when I click it checkbox with days will show and when I choose a day it will automatically put in the table, however instead of updating specific row, changes are applied in all row. What I want to happen is for example I click add available day in first row then first row data must be updated not second and third row
This is my code:
import React from 'react';
import { Table, Button } from 'react-bootstrap';
const personData = [
{ id: 1, firstName: 'test1', lastName: 'test', day: [] },
{ id: 2, firstName: 'Jane', lastName: 'Doe', day: [] },
{ id: 3, firstName: 'John', lastName: 'Doe', day: [] },
{ id: 4, firstName: 'Clint', lastName: 'test', day: [] }
]
export default class App extends React.Component {
constructor() {
super();
this.state = {
day: [],
isSelectDay: false,
person: personData
}
}
handleSelectDay = (event) => {
let dayArr = [...this.state.day]
const value = event.target.value
const index = dayArr.findIndex(day => day === value);
if (index > -1) {
dayArr = [...dayArr.slice(0, index), ...dayArr.slice(index + 1)]
} else {
dayArr.push(value)
}
this.setState({ day: dayArr });
}
handleAddDay = () => {
this.setState({ isSelectDay: true })
}
render() {
const { isSelectDay, day } = this.state
const dayOptions = ["Monday, ", "Tuesday, ", "Wednesday", "Thursday, ", "Friday"].map((cur, ind) => {
return (
<div key={ind} className="checks" >
<label>
<input type="checkbox" name={cur} value={cur}
onChange={this.handleSelectDay} />{cur}
</label>
</div>
)
})
return (
<>
<Table striped bordered hover>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Days Available</th>
</tr>
</thead>
<tbody>
{this.state.person.length > 0 ? (
this.state.person.map((person) => (
<tr key={person.id}>
<td>{person.firstName}</td>
<td>{person.lastName}</td>
<td>{day}<Button variant="success" onClick={this.handleAddDay}>Add Available Day</Button></td>
</tr>
))
) : (
<tr>
<td colSpan={3}>No Data</td>
</tr>
)}
</tbody>
</Table>
<div style={{ display: isSelectDay ? 'block' : 'none' }}>
{dayOptions}
</div>
</>
)
}
}
Is this something you're after?
Demo
Full Code
I changed isSelectDay to personSelected so when you click 'Add Available Day' it'll switch to the correct person object from personData. I then used this to update the people object in the state (a copy of personData) to add/remove days from day array. The day array was then used to output the days.
import React from "react";
import { Table, Button } from "react-bootstrap";
var personData = [
{ id: 1, firstName: "test1", lastName: "test", day: [] },
{ id: 2, firstName: "Jane", lastName: "Doe", day: [] },
{ id: 3, firstName: "John", lastName: "Doe", day: [] },
{ id: 4, firstName: "Clint", lastName: "test", day: [] }
];
export default class App extends React.Component {
constructor() {
super();
this.state = {
personSelected: null,
people: personData
};
}
handleSelectDay = (event) => {
let dayArr = [...this.state.personSelected.day];
const value = event.target.value;
const index = dayArr.findIndex((day) => day === value);
if (index > -1) {
dayArr = [...dayArr.slice(0, index), ...dayArr.slice(index + 1)];
} else {
dayArr.push(value);
}
let newPeople = this.state.people;
newPeople.find((x) => x === this.state.personSelected).day = dayArr;
this.setState({ people: newPeople });
};
handleAddDay = (person) => {
this.setState({ personSelected: person });
document
.querySelectorAll("input[type=checkbox]")
.forEach((el) => (el.checked = false));
};
render() {
const { personSelected } = this.state;
const dayOptions = [
"Monday, ",
"Tuesday, ",
"Wednesday",
"Thursday, ",
"Friday"
].map((cur, ind) => {
return (
<div key={ind} className="checks">
<label>
<input
type="checkbox"
name={cur}
value={cur}
onChange={this.handleSelectDay}
/>
{cur}
</label>
</div>
);
});
return (
<>
<Table striped bordered hover>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Days Available</th>
</tr>
</thead>
<tbody>
{this.state.people.length > 0 ? (
this.state.people.map((person) => (
<tr key={person.id}>
<td>{person.firstName}</td>
<td>{person.lastName}</td>
<td>
{person.day}
<Button
variant="success"
onClick={() => this.handleAddDay(person)}
>
Add Available Day
</Button>
</td>
</tr>
))
) : (
<tr>
<td colSpan={3}>No Data</td>
</tr>
)}
</tbody>
</Table>
{personSelected !== null && (
<div style={{ display: "block" }}>{dayOptions}</div>
)}
</>
);
}
}
I have data that I need to show in table, for all rows I would like to use collapse function. Now I have working code that is collapsing all rows on click, but in what way I can collapse only one already clicked?
This is my code:
class Data extends React.Component {
constructor(props) {
super(props);
this.state = {
datas: [
{name: "or1", status: 11},
{name: "or3", status: 2},
{name: "or2", status: 22},
],
expanded: [],
isOpen: true,
};
}
toogleContent(openIs) {
this.setState({
isOpen: !openIs
})
}
render() {
return (
<Table responsive>
<thead className="text-primary">
<tr>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{this.state.datas.map((data, i) => (
<tr id={i} onClick={this.toogleContent.bind(this, this.state.isOpen)}>
<td>{data.name}</td>
<td><Collapse isOpen={this.state.isOpen}>
{data.status}</Collapse>
</td>
</tr>
))}
</tbody>
</Table>
)
}
}
I used their indexes to find out if they are opened or not, but you can use their names too, or add at data object a key isOpened =>
state={
isOpenIndexes = []
}
toogleContent(index) {
// we check if already opened
this.state.isOpenIndexes.find(openedIndex => openedIndex ===index ) ?
this.setState({
isOpenIndexes: this.state.isOpenIndexes.filter(openedIndex => openedIndex!==index)
})
:
this.setState({
isOpenIndexes: isOpenIndexes.concat([index])
})
}
{datas.map((data, i) => (
<tr id={i} onClick={this.toogleContent.bind(this, i)} isOpened={this.state.isOpenIndexes.find(openedIndex => openedIndex ===i )}>
<td>{data.name}</td>
<td>{data.status}</td>
</tr>
))}
I have A react component which renders a list of items that have been called from an API and set to setOfAllBooks state. Any time I search for the item, setOfAllBooks state is filtered through by the search ternm and the results are held in searchedBooks state. The results of searchedBooks are then passed to Table component and rendered in a list. At this point it works correctly, but when I search for another item it gets clustered in the Table. What I want to do is anytime I search a new Item after I have searched for a previos term I want the list-items in the Table component to be cleared to make way for the new items that have been searched.
import React, { Component } from 'react';
import './Home.css'
import axios from 'axios';
import Autosuggest from 'react-autosuggest';
var books = []
const getSuggestions = value => {
const inputValue = value.trim().toLowerCase();
const inputLength = inputValue.length;
return inputLength === 0 ? [] : books.filter(book =>
book.title.toLowerCase().slice(0, inputLength) === inputValue);
};
const getSuggestionValue = suggestion => suggestion.title;
const renderSuggestion = suggestion => (
<div>
{suggestion.title}
</div>
);
const Table = ({ data }) => (
<table class="table table-hover">
<thead>
<tr class="table-primary">
<th scope="col">Title</th>
<th scope="col">Author</th>
<th scope="col">ISBN</th>
<th scope="col">No. Of Copies</th>
</tr>
</thead>
<tbody>
{data.map(row =>
<TableRow row={row} />
)}
</tbody>
</table>
)
const TableRow = ({ row }) => (
<tr class="table-light">
<th scope="row" key={row.title}>{row.title}</th>
<td key={row.author}>{row.author}</td>
<td key={row.isbn}>{row.isbn}</td>
<td key={row.isbn}>24</td>
</tr>
)
class Home extends Component {
constructor(props) {
super(props);
this.state = {
value: '',
suggestions: [],
setOfAllBooks: [],
searchedBooks: []
};
this.searchBook = this.searchBook.bind(this);
}
componentDidMount(){
axios.get('/api/book/viewAll')
.then(res => {
this.setState({ setOfAllBooks: res.data });
books = this.state.setOfAllBooks;
console.log(this.state.setOfAllBooks)
})
}
onChange = (event, { newValue }) => {
this.setState({
value: newValue
});
};
onSuggestionsFetchRequested = ({ value }) => {
this.setState({
suggestions: getSuggestions(value)
});
};
onSuggestionsClearRequested = () => {
this.setState({
suggestions: []
});
}
searchBook(event){
event.preventDefault();
this.setState({value: this.state.value});
this.state.searchedBooks = this.state.setOfAllBooks.filter(book => book.title == this.state.value);
this.setState({searchedBook: []})
console.log(this.state.searchedBook);
}
render() {
const { value, suggestions } = this.state;
const inputProps = {
placeholder: 'Enter the name of the book',
value,
onChange: this.onChange
}
return (
<div class="form-group col-lg-4">
<label for="exampleInputEmail1">Email address</label>
<Autosuggest
suggestions={suggestions}
onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
onSuggestionsClearRequested={this.onSuggestionsClearRequested}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
inputProps={inputProps}
id="searchFor"
/>
<div className=" form-group">
<label htmlFor="searchFor"> </label>
<button class="form-control btn btn-success" type="submit" onClick={this.searchBook}>Search</button>
</div>
<Table data={this.state.searchedBooks} />
</div>
)
}
}
export default Home;
The results
The Error
You need to add the key prop to the TableRow component as <TableRow key={row.title} row={row} />. Remove the key where you have right now.
.... A good rule of thumb is that elements inside the map() call need keys.
... keys used within arrays should be unique among their siblings. . Doc.
So, it seems title what you used for key will still throw warnings, as they are not uniqe. If you have ID attribute in the row object use that. Adding key to TableRow will remove the first warning, but other warning still be there until title doesn't have the uniq values across all the data.
I have a React form that currently stores one form fields value in the items array. However, when adding more than one field, I can't get the content of the other fields to be stored in the array as well. It currently stores the value of the First Name input, but can't figure out the Last Name and Phone fields. The data is then rendered to the items array to a 3 column table, but can't get the other fields to show in their respective columns.
Contacts.js
import ContactList from "./ContactList";
class Contacts extends Component {
constructor(props) {
super(props);
this.state = {
items: []
};
this.addItem = this.addItem.bind(this);
this.deleteItem = this.deleteItem.bind(this);
}
addItem(e) {
if(this._inputElement.value !== "") {
var newItem = {
firstname: this._inputElement.value,
lastname: this._inputElement2.value,
phonename: this._inputElement3.value,
key: Date.now()
};
this.setState((prevState) => {
return {
items: prevState.items.concat(newItem)
};
});
this._inputElement.value = "";
this._inputElement2.value = "";
this._inputElement3.value = "";
}
console.log(this.state.items);
e.preventDefault();
}
deleteItem(key) {
var filteredItems = this.state.items.filter(function (item) {
return (item.key !== key);
});
this.setState({
items: filteredItems
});
}
render () {
return (
<Panel>
<Tabs onChange={this.onChange} defaultSelectedIndex={0} justified={true}>
<Tab value="pane-1" label="Add Contact" onActive={this.onActive}>
<Form onSubmit={this.addItem}>
<input ref={(a) => this._inputElement = a}
placeholder="First Name" />
<input ref={(a) => this._inputElement2 = a}
placeholder="Last Name" />
<input ref={(a) => this._inputElement3 = a}
placeholder="Phone" />
<Button variant="raised">Add</Button>
</Form>
</Tab>
<Tab value="pane-2" label="List Contacts">
<ContactList entries={this.state.items}
delete={this.deleteItem}/>
</Tab>
</Tabs>
</Panel>
);
}
}
export default Contacts
Contact List
class ContactList extends Component {
constructor(props) {
super(props);
this.createContact = this.createContact.bind(this);
}
delete(key) {
this.props.delete(key);
}
createContact(item) {
return
<tr key={item.key}>
<td onClick={() => this.delete(item.key)}>{item.firstname}</td>,
<td>{item.lastname}</td>
<td>{item.phone}</td>
</tr>
}
render() {
var contactEntries = this.props.entries;
var listItems = contactEntries.map(this.createContact);
return (
<table className="mui-table">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr>
{listItems}
</tr>
</tbody>
</table>
);
}
};
export default ContactList;
Here is the answer. You are just hitting this._inputElement ref only saving its value whereas in your form you have two more inputs. My suggestion check latest updates react updates. They don't advice you to use "REF" at all.
addItem(e) {
if (this._inputElement.value !== "") {
var newItem = {
firstname: this._inputElement.value,
lastname: this._inputElement2.value,
phonename: this._inputElement3.value,
key: Date.now()
};
this.setState(prevState => {
return {
items: prevState.items.concat(newItem)
};
});
this._inputElement.value = "";
this._inputElement2.value = "";
this._inputElement3.value = "";
}
import React, { Component } from 'react';
import {Doughnut} from "react-chartjs-2"
import {bindActionCreators} from "redux";
import {connect} from 'react-redux';
import {fetchBeacons} from '../actions/';
const DummyDoughnutData = {
labels: ['beacon 1 - zone a', 'beacon 2 - zone c', 'beacon 3 - zone a', 'beacon 4 - zone b', 'beacon 5 - zone b'],
datasets: [
{
borderColor: 'rgba(255,255,255,.55)',
data: [ 30, 9, 17, 22, 11],
backgroundColor: [
'#063e70',
'#107bb5',
'#1A1C1D',
'#666666',
'#2F4F4F'
]
}
],
};
// const beacons=[
// {zone:"zone a", status: "active", _id:1},
// {zone:"zone c", status: "active", _id:2},
// {zone:"zone a", status: "active", _id:3},
// {zone:"zone b", status: "active", _id:4},
// {zone:"zone b", status: "active", _id:5},
// {zone:"zone b", status: "active", _id:6},
// {zone:"zone c", status: "active", _id:7}
// ];
// class BeaconZoneRow extends Component {
// render() {
// return (
// <tr>
// <th colSpan="2">
// {this.props.zone}
// </th>
// </tr>
// )
// }
// }
class BeaconRow extends Component {
render() {
return (
<tr>
<td>{this.props.beacon.name}</td>
<td>{JSON.stringify(this.props.beacon.status)}</td>
<td> {this.props.beacon.zone.name} </td>
</tr>
)
}
}
class BeaconList extends Component {
// Sort = (prop) => { return (a,b) => a[prop].localeCompare(b[prop])};
render() {
const rows = [];
this.props.beacons.map( beacon => {
return rows.push(<BeaconRow beacon={beacon} key={beacon._id}/>)
});
return (
<div className="col-lg-6">
<table className="table">
<thead>
<tr>
<th>Name</th>
<th>Status</th>
<th>Zone</th>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>
</div>
)
}
}
class BeaconDoughnutAnalysis extends Component {
render() {
return (
<div className="col-lg-6">
<Doughnut data={DummyDoughnutData} />
<br/>
<center>visits</center>
</div>
)
}
}
class BeaconListComponent extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this)
}
handleSubmit(){
this.props.router.push('/new-beacon');
}
componentWillMount = () => {
this.props.fetchBeacons();
};
render() {
return (
<div>
<div className="row">
<div className="col-sm-5">
<button className="btn btn-sm btn-info" onClick={this.handleSubmit}> Add Beacon</button>
</div>
</div>
<br/>
{ this.props.beacons && this.props.beacons.length > 0 ?
<div className="row">
<BeaconList beacons={this.props.beacons}/>
<BeaconDoughnutAnalysis/>
</div> :
<center><h1>...Loading</h1></center>
}
</div>
)
}
}
function mapStateToProps(state) {
return {
beacons: state.beacons
}
}
function matchDispatchToProps(dispatch){
return bindActionCreators({fetchBeacons: fetchBeacons}, dispatch);
}
export default connect(mapStateToProps, matchDispatchToProps)(BeaconListComponent);
i had fetched data from the server and i wanted to know how to filter that data in the table using react redux
the code is shown above using which table is being displayed and i wanted to filter its contents
Assuming you are providing the zone as a prop to the BeaconList component you just need to provide a check while mapping like below
class BeaconList extends Component {
// Sort = (prop) => { return (a,b) => a[prop].localeCompare(b[prop])};
render() {
const rows = [];
//Assuming you are filtering based on zone and you are giving the zone you want to filter as a prop zone
this.props.beacons.map( beacon => {
if(beacon.zone === this.props.zone) {
return rows.push(<BeaconRow beacon={beacon} key={beacon._id}/>)
}
});
return (
<div className="col-lg-6">
<table className="table">
<thead>
<tr>
<th>Name</th>
<th>Status</th>
<th>Zone</th>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>
</div>
)
}
}
I hope this helps