How to add, update and delete row from table dynamically in reactjs - javascript

I am new in reactJS.
Here, I make a file in which I have made a form and table.
I have added some static data in to the table already. But, I want to add, update and delete rows dynamically.
How can I achieve this?
Here is my code In which the insert, update and delete function are there.
What will be the correct code for that? Thanks in advance.
import React, { Component } from 'react';
import classes from './Product.css';
import { Link } from 'react-router-dom';
class Product extends Component {
state = {
name: '',
category: '',
price: '',
formErrors: ''
}
handleUserInputs = (e) => {
const name = e.target.name;
const value = e.target.value;
this.setState({ [name]: value });
}
insertHandler = (e) => {
if (this.state.name === '' || this.state.name === null) {
this.setState({ formErrors: 'Blank Name' });
}
else if ((this.state.category === '' || this.state.category === null)) {
this.setState({ formErrors: 'Blank Category' });
}
else if (this.state.price === '' || this.state.price === null || typeof this.state.price === 'undefined') {
this.setState({ formErrors: 'Blank Price' });
}
else if (!this.state.price.match(/^[0-9\b]+$/)) {
this.setState({ formErrors: 'Price should be in digits only.' });
}
else {
// insert code will be here
}
e.preventDefault();
}
editHandler = (e) => {
// update code will be here
}
deleteHandler = (e) => {
// delete row code will be here.
}
render() {
const data = [
{ "id": 1,
"name": "Chips",
"category": "Food",
"price": "20"
},
{
"id": 2,
"name": "Shirt",
"category": "Clothes",
"price": "500"
},
{
"id": 3,
"name": "Mobile",
"category": "Electronics",
"price": "10000"
}
];
return (
<div className={classes.main}>
<div className={classes.Product}>
<div className={classes.product_box_body}>
<form className={classes.form} onSubmit={this.handleSubmit}>
<h2>Add Product</h2>
<div className={classes.name}>
<input type="text" name="name" className={classes.form_control} placeholder="Product Name" value={this.state.name} onChange={(e) => this.handleUserInputs(e)} />
</div>
<div className={classes.category}>
<select className={classes.form_control} name="category" onChange={(e) => this.handleUserInputs(e)} aria-required="true">
<option value="">-- Select any Category --</option>
<option value="Food">Food</option>
<option value="Electronics">Electronics</option>
<option value="Clothes">Clothes</option>
</select>
</div>
<div className={classes.price}>
<input type="text" name="price" className={classes.form_control} placeholder="Price" value={this.state.price} onChange={(e) => this.handleUserInputs(e)} />
</div>
<p className={classes.text_red}>{this.state.formErrors}</p>
<button type="submit" className={classes.product} onClick={(e) => this.insertHandler(e)}>Insert</button>
<Link to="/login" className={classes.cancel}>Cancel</Link>
</form>
</div>
</div>
<div>
<table className={classes.table}>
<thead>
<tr>
<th style={{height: '50px'}}>Name</th>
<th style={{height: '50px'}}>Category</th>
<th style={{height: '50px'}}>Price</th>
<th style={{height: '50px'}}>Action</th>
</tr>
</thead>
<tbody>
{data.map(obj => {
return (
<tr>
<td style={{width: '50px'}}>
{obj.name}
</td>
<td style={{width: '50px'}}>
{obj.category}
</td>
<td style={{width: '50px'}}>
{obj.price}
</td>
<td style={{width: '120px'}}>
<button type="submit" name="Edit" value="edit" onClick={(e) => this.editHandler(e)}>Edit</button> <button type="submit" name="Delete" value="delete" onClick={(e) => this.deleteHandler(e)}>Delete</button>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
);
}
}
export default Product;

you need to manage your array data in the state, you need :
state={data=[]} and then your delete function erase data of you array and then you need to call the method setState who render de component with the new data merge and the same to update , you modify your array data and later call setState and magic happend, you can asing your data to state in the constructor o componentDidMount method

Related

How do I display data from my json file that match my filters

I'm creating a multi steps form in React and I want a page (Filters.jsx) in my form, that returns me all the menus name (contained in data.json) that matches my filters ( beaf, chicken, vegetables), but I don't kow how to do that.
import React from "react";
export default function Filter() {
return (
<div className="flex flex-col">
<div className=" w-full mx-2 flex-1">
<div className="font-bold h-6 mt-3 text-gray-600 leading-8 uppercase ">
{" "}
Norms
</div>
<tbody className="bg-white my-2 p-1 flex borer border-gray-200 rounded text-gray-500">
<tr>
<td className="font-bold h-8 mt-5 leading-8 uppercase ">
<td>
<input type="checkbox" value="beaf" className="w-8 h-3" /> beaf
</td>
<td>
<input type="checkbox" value="chicken" className="w-8 h-3" />
chicken
</td>
<td>
<input type="checkbox" value="vegetables" className="w-8 h-3" />
vegetables
</td>
</td>
</tr>
</tbody>
</div>
</div>
);
}
Here is the link of my sandbox ( browse /menu/form to see the form): https://codesandbox.io/s/unruffled-river-ktoic8?
What I tried:
export default function Filters() {
//Filters events
const ref = [
{ name: "beaf" },
{ name: "chicken" },
{ name: "vegetables" }
]
const [norms, setNorms] = useState([]);
useEffect(() => {
setNorms(ref);
}, []);
const handleChange = (e) => {
const { name, checked } = e.target;
let tempR = norms.map((r) =>
r.name === name ? { ...r, isChecked: checked } : r
);
setNorms(tempR);
}
return (
<div>
<form className="form w-100">
{
norms.map((e, index) => (
<div className="form-check" key={index}>
<input
type="checkbox"
className="form-check-input"
name={e.name}
checked={e?.isChecked || false}
onChange={handleChange}
/>
<label className="form-check-label ms-2">{e.name}</label>
</div>
))
}
</form >
</div>
)
I suggest using an object or Map to hold the filter values where the filter name is the key and the checked value is the value.
const [filters, setFilters] = React.useState({});
Create a handler that sets the checked value for a specific input by name.
const changeHandler = (e) => {
const { name, checked } = e.target;
setFilters((filters) => ({
...filters,
[name]: checked
}));
};
Render the inputs and set the checked prop from state.
{["beef", "chicken", "vegetables"].map((name) => (
<td key={name}>
<label>
<input
type="checkbox"
checked={filters[name]}
onChange={changeHandler}
name={name}
className="w-8 h-3"
/>
{name}
</label>
</td>
))}
And then filter/map the data, all inline.
import data from "../../data.json";
...
{data
.filter((item) => {
// get array of enabled filter keys
const filterEntries = Object.entries(filters)
.filter(([, value]) => Boolean(value))
.map(([key]) => key);
// some filter enabled
if (filterEntries.length) {
// check proteins
if (filters.beef || filters.chicken) {
return item.dishes.some((dish) =>
filterEntries.includes(dish.meat)
);
}
// check vegetables
if (filters.vegetables) {
return item.dishes.some((dish) => !!dish.vegetables);
}
}
// no filter enabled, return all elements
return true;
})
.map((item) => (
<tr key={item.id}>
.... map data item properties here ...
</tr>
))}

ReactJS: fakepath issue in repeater

I have created a repeater, so when user clicks on plus icon then a new row with two input tags is appended. Below is my code :
repeater.js
import React from "react"
const Details = (props) => {
return (
props.Desc !== '' ?
props.Desc.map((val, idx) => {
let desc = ` desc-${idx}`, file = `file-${idx}`
return (
<tr key={val.index}>
<td> Description</td>
<td >
<input type="text" defaultValue={val.desc} name="desc" data-id={idx} id={desc} className="form-control " />
</td>
<td className="mr-2"> Files</td>
<td>
<input type="file" defaultValue={file} name="file" id={file} data-id={idx} className="form-control " />
</td>
<td>
{
idx === 0 ? <button onClick={() => props.add()} type="button" className="btn btn-primary text-center"><i className="fa fa-plus-circle" aria-hidden="true"></i></button>
: <button className="btn btn-danger" onClick={(() => props.delete(val))} ><i className="fa fa-minus" aria-hidden="true"></i></button>
}
</td>
</tr >
)
})
: null
)
}
export default Details
Details.js
import React, { Fragment, Component } from 'react'
import Details from './repeater.js'
class CreateDetail extends Component {
constructor(props) {
super(props);
this.state = {
inputList: [{ index: Math.random(), desc: "", file: "" }],
}
}
onSubmit = (e) => {
console.log('data : ', this.state.inputList[0]);
}
handleChange = (e) => {
if (["desc", "file"].includes(e.target.name)) {
let Desc = [...this.state.inputList]
inputList[e.target.dataset.id][e.target.name] = e.target.value;
} else {
this.setState({ [e.target.name]: e.target.value })
}
}
addNewRow = (e) => {
this.setState((prevState) => ({
inputList: [...prevState.inputList, { index: Math.random(), desc: "", file: "" }],
}));
}
deteteRow = (index) => {
this.setState({
inputList: this.state.inputList.filter((s, sindex) => index !== sindex),
});
}
clickOnDelete(record) {
this.setState({
inputList: this.state.inputList.filter(r => r !== record)
});
}
render() {
let { inputList, flag } = this.state
return (
<Fragment>
<div className="container-fluid">
<div className="row">
<div className="col-sm-12">
<div className="card">
<div className="card-body">
<form className="needs-validation" onChange={this.handleChange}>
<div className="form-group row">
<label className="col-xl-3 col-md-3">Details</label>
<div className="col-9 col-md-9">
<table className="table">
<tbody>
<Details add={this.addNewRow} delete={this.clickOnDelete.bind(this)} Desc ={inputList} />
</tbody>
</table>
</div>
</div>
<div className="pull-right">
<button type="button" className="btn btn-primary" onClick={this.onSubmit}> save </button>
</div>
</form>
</div>
</div>
</div>
</div >
</div >
</Fragment >
)
}
}
export default CreateDetail
But I am facing one issue, when I use the input tag's type "file" and I upload an image then I am receiving the fakepath as shown below.
C:\fakepath\6t8Zh249QiFmVnkQdCCtHK.jpg
I am encountering this problem only in repeater. If I use an input tag with type "file", outside the repeater then I am receiving the correct path.
The fake path is the main issue because if I extract the file name and upload it to s3 then empty image is uploaded to s3.
How can I upload a file in repeater?
the browser will not allow getting the local path of the file.you can use the data as form data and store it in state and can send it to S3.
like
handleChange = (e) => {
let formData = new FormData
for (var i = 0; i < e.target.files.length; i++) {
formData.append(e.target.name, e.target.files[i])
}
.....
}

Deleting Dynamic Element Reactjs

--FieldSection.js--
import React, { Component } from 'react';
import Field from './Field.js';
class FieldSection extends Component{
constructor(props){
super(props);
this.state ={
numberOfFields: 1
}
}
addField = () => {
const { numberOfFields } = this.state;
this.setState({ numberOfFields: numberOfFields + 1 });
}
listFields = (numberOfFields) => {
var fields = [];
for(var i=0; i<numberOfFields; i++){
fields.push(
(<Field number={i} />)
)
}
return fields;
}
render () {
const {listFields, addField} = this;
const {numberOfFields} = this.state;
return (
<div>
<label><u>Fields</u></label>
{listFields(numberOfFields)}
<div id="fieldButtons">
<button id="addField" type="button" onClick={addField}> Add Field </button>
<button id="removeField" type="button"> Remove Field </button>
</div>
</div>
)
}
}
export default FieldSection;
-----------------Field.js-------------------
import React from 'react';
class Field extends React.Component {
constructor(props){
super(props);
this.state = {
value: 'empty',
specVisible: 'hidden',
display: 'none'
};
}
SelectChange = (event) => {
this.setState({value: event.target.value});
if(event.target.value === "string" )
{
this.setState({specVisible: 'visible'});
this.setState({display: 'block'});
}
else {
this.setState({specVisible: 'hidden'})
this.setState({display: 'none'})
}
}
render (){
const {SelectChange} = this;
const {value, specVisible, display} = this.state;
return (
<div>
<div>
<label><strong>New Field </strong></label>
<div id="remove-" className="remove" style={{display: "inline", visibility: "hidden"}}>
<label> --Remove </label> <input type="checkbox" id="removeBox" className="rmvCheckbox" />
<br />
</div>
<label> Name: </label>
<input id="name-" className="name" type="text" name="name" /> <br />
<label> Description: </label>
<input id="description-" className="description" name="description" /> <br />
<label> Datatype: </label>
<select value={value} onChange={SelectChange} id={`selectData-${this.props.number}`} className="selectData" name="selectData" /*onClick={AddListener}*/>
<option value="empty"> </option>
<option value="string"> String </option>
<option value="character"> Character </option>
<option value="timestamp"> Timestamp </option>
<option value="integer"> Integer </option>
<option value="long"> Long </option>
<option value="double"> Double </option>
<option value="boolean"> Boolean </option>
</select> <br />
</div>
<div id={`specifySection-${this.props.number}`} className="specifySection" style={{visibility: specVisible, display: display}} >
<label> Specify Length: </label>
<input className="specifyLength" type="text" name="length"/> <br />
</div>
</div>
)}
}
export default Field
I am trying to implement a feature where you click "Remove Field" button and a list of checkboxes next to all the new fields appears. Whenever you confirm the deletion, it would delete all the elements that are selected.
Obviously I could subtract one to the numberOfFields state, however I want to delete specific elements, rather than just the last field.
What would that look like?
You can do it as follows. The basic idea is to get all the ids of the fields that need to be deleted and iterate over them and delete all the components corresponding to these ids.
Sandbox for code
When addField is called fields state of FieldsSelection
component is updated by adding a key with unique id, with the Field
component as its value along with all the props.
The remove state tracks if remove Field has been clicked and
toggles the remove checkbox in each Field component by passing it
as a prop.
fieldsToRemove state is updated via the markFields prop in
Field component each time a remove field checkbox is clicked.
When deleteFields is called, it iterates over the fieldsToRemove
state and removes the corresponding components from the fields
state object.
I used uuid package for unique ids for each Field as opposed to deleting
via index, which is not a great way and also conflicts with the key prop of
react.
FieldSection.js
import React, { Component } from "react";
import Field from "./Field.js";
import { v4 } from "uuid";
class FieldSection extends Component {
constructor(props) {
super(props);
this.state = {
fields: {},
remove: false,
fieldsToRemove: []
};
}
addField = () => {
const fields = this.state.fields;
const id = v4();
fields[id] = <Field key={id} id={id} mark={this.markFields} />;
this.setState({ fields });
};
listFields = () => {
var ids = Object.keys(this.state.fields);
return ids.map(id => {
return React.cloneElement(this.state.fields[id], {
remove: this.state.remove
});
});
};
markFields = (checked, i) => {
if (checked) {
const arr = [...this.state.fieldsToRemove];
arr.push(i);
this.setState({ fieldsToRemove: arr });
} else {
const arr = this.state.fieldsToRemove.filter(x => i !== x);
this.setState({ fieldsToRemove: arr });
}
};
removeFields = () => {
this.setState({ remove: !this.state.remove });
};
deleteFields = () => {
const fields = { ...this.state.fields };
this.state.fieldsToRemove.forEach(id => {
delete fields[id];
});
this.setState({ fields, fieldsToRemove: [], remove: false });
};
render() {
const { listFields, addField, removeFields, deleteFields } = this;
const { numberOfFields, remove } = this.state;
return (
<div>
<label>
<u>Fields</u>
</label>
{listFields()}
<div id="fieldButtons">
<button id="addField" type="button" onClick={addField}>
{" "}
Add Field{" "}
</button>
<button id="removeField" type="button" onClick={removeFields}>
{" "}
Remove Field{" "}
</button>
<br />
<button type="button" onClick={deleteFields}>
{" "}
Delete Fields{" "}
</button>
</div>
</div>
);
}
}
export default FieldSection;
Field.js
import React from "react";
class Field extends React.Component {
constructor(props) {
super(props);
this.state = {
value: "empty",
specVisible: "hidden",
display: "none"
};
}
SelectChange = event => {
this.setState({ value: event.target.value });
if (event.target.value === "string") {
this.setState({ specVisible: "visible" });
this.setState({ display: "block" });
} else {
this.setState({ specVisible: "hidden" });
this.setState({ display: "none" });
}
};
render() {
const { SelectChange } = this;
const { value, specVisible, display } = this.state;
const styles = this.props.remove
? { display: "inline", visibility: "visible" }
: { display: "inline", visibility: "hidden" };
return (
<div>
<div>
<label>
<strong>New Field </strong>
</label>
<div id="remove-" className="remove" style={styles}>
<label> --Remove </label>{" "}
<input
type="checkbox"
id="removeBox"
className="rmvCheckbox"
onChange={e => {
this.props.mark(e.target.checked, this.props.id);
}}
/>
<br />
</div>
<label> Name: </label>
<input id="name-" className="name" type="text" name="name" /> <br />
<label> Description: </label>
<input
id="description-"
className="description"
name="description"
/>{" "}
<br />
<label> Datatype: </label>
<select
value={value}
onChange={SelectChange}
id={`selectData-${this.props.number}`}
className="selectData"
name="selectData" /*onClick={AddListener}*/
>
<option value="empty"> </option>
<option value="string"> String </option>
<option value="character"> Character </option>
<option value="timestamp"> Timestamp </option>
<option value="integer"> Integer </option>
<option value="long"> Long </option>
<option value="double"> Double </option>
<option value="boolean"> Boolean </option>
</select>{" "}
<br />
</div>
<div
id={`specifySection-${this.props.number}`}
className="specifySection"
style={{ visibility: specVisible, display: display }}
>
<label> Specify Length: </label>
<input className="specifyLength" type="text" name="length" /> <br />
</div>
</div>
);
}
}
export default Field;

React Js : Passing Data from Parent To More Than One Child Component

I am a newbie in ReactJs , Initially I was able to pass data from Parent to child using state objects . For Now I am able to pass only from Parent To One Child Component , I need to pass the same to another Child Component and when I do that using the same technique I am unable to get the data in second child component ,it says undefined . Frome Parent-> Blank -> Child 1-> Display Details -> Child2 -> Phone . Please suggest
In Parent
-> I am able to retrieve in Child 1
-> I am unable to retrieve in Phone that is Child 2
import React, { PropTypes , Component } from 'react';
import './blank.css';
import {
Panel,
Button,
PageHeader,
ControlLabel,
FormControl,
Pagination,
FormGroup} from 'react-bootstrap';
import JwPagination from 'jw-react-pagination';
import FormControlFeedback from 'react-bootstrap/lib/FormControlFeedback';
import FormControlStatic from 'react-bootstrap/lib/FormControlStatic';
import InputGroupAddon from 'react-bootstrap/lib/InputGroupAddon';
import {Link, BrowserRouter as Router,Route} from 'react-router-dom';
const customStyles = {
ul: {
backgroundColor: 'red'
},
li: {
border: '1px solid green'
},
a: {
color: 'blue'
}
};
const title = 'Customer-LookUp';
const spacing = {
marginRight: "20px",
marginbottom: "20px"
}
const buttonalignment = {
marginLeft: "81px",
marginbottom: "20px"
}
class displayBlank extends Component {
constructor(props) {
super(props);
this.state = {
newData: [],
pageOfItems: [],
respData:[],
sort: {
column: null,
direction: 'desc',
}
};
this.handleSubmit = this.handleSubmit.bind(this);
this.searchFunction = this.searchFunction.bind(this);
this.setArrow = this.setArrow.bind(this);
this.onSort = this.onSort.bind(this);
this.onChangePage = this.onChangePage.bind(this);
this.handleClick = this.handleClick.bind(this);
};
onChangePage(pageOfItems) {
// update local state with new page of items
this.setState({pageOfItems});
}
handleSubmit(event) {
event.preventDefault();
const form = event.target;
const data = new FormData(form);
const arrayValue = [];
var i = 0;
console.log('Data from Form:',data);
for (let name of data.keys()) {
const input = form.elements[name];
const parserName = input.dataset.parse;
const parsedValue = data.get(name);
console.log('name',name);
console.log('parsedValue',parsedValue);
if (typeof(parsedValue) == 'undefined' || parsedValue == null) {
console.log('Not Defined or Not Null')
arrayValue[i] = "";
data.set(name, arrayValue[i]);
}
else{
data.set(name, parsedValue);
arrayValue[i] = parsedValue;
}
i=i+1;
}
console.log('brandname:after get',arrayValue[0]);
console.log('LastName:after get',arrayValue[2]);
console.log('zipcode:after get',arrayValue[8]);
var response_data = "";
var response_jsonObj ;
var txt = "";
var req = {"CustomerLookupRequest" : [{
"Field1":arrayValue[0],
"Field2": arrayValue[1],
"Field3":arrayValue[2],
"Field4":arrayValue[3],
"Field5":arrayValue[4],
"Field6":arrayValue[5],
"Field7":arrayValue[6],
"Field8":arrayValue[7],
"Field9":arrayValue[8],
"Field10":arrayValue[9]
}]
};
console.log('req string :' + req);
fetch('API_URL', {
headers: {
'Accept': 'application/json, text/plain, application/xml, */*',
'Content-Type': 'application/json' ,
'Access-Control-Allow-Headers': 'Content-Type',
},
method: 'POST',
body: JSON.stringify(req)}
).then(response => {
if (response.status !== 200) {
console.log('Problem in fetching');
return;
}
response.text().then(data => {
console.log('Data in Console',data);
response_data = data;
console.log('Response Data',response_data);
response_jsonObj = JSON.parse(response_data);
console.log('Response JSON Object',response_jsonObj);
this.setState({ newData:response_jsonObj});
//console.log('customer Data in handle submit',customerData);
});
}).catch(error => this.setState({ error }));
}
handleClick(field1,field2){
var ID = field1;
var Name = field2;
var newresponse_jsonObj,response_data;
var req ={"GetCustomerRequest": [{
"field1": field2,
"field2": "xyz",
"field3": field1,
"field4": "",
"field5": "",
"field6": ""
}]
};
fetch('API_URL', {
headers: {
'Accept': 'application/json, text/plain, application/xml, */*',
'Content-Type': 'application/json' ,
'Access-Control-Allow-Headers': 'Content-Type',
},
method: 'POST',
body: JSON.stringify(req)}
).then(response => {
if (response.status !== 200) {
console.log('Problem in fetching');
return;
}
response.text().then(data => {
response_data = data;
//console.log('Response Data in Handle Click for Get-Customer',response_data);
newresponse_jsonObj = JSON.parse(response_data);
console.log('Response JSON Object for Get-Customer',newresponse_jsonObj);
this.setState({respData:newresponse_jsonObj});
this.setState({ pageOfItems:newresponse_jsonObj});
this.getDetails();
});
}).catch(error => this.setState({ error }));
}
getDetails(){
console.log('Get Customer Method:');
<table>
<tbody>
{this.state.pageOfItems.map((item, i) => {
return (
<tr key={i} >
<td >{item.XYZ.Field1}</td>
<td> {item.XYZ.Field2}</td>
<td> {item.XYZ.Field3}</td>
<td> {item.XYZ.Field4}</td>
<td> {item.Field5}</td>
</tr>
);
})}
</tbody>
</table>
}
searchFunction() {
var input, filter, table, tr, td, td1, i;
input = document.getElementById("search");
filter = input.value.toUpperCase();
console.log('input in searchFunction:',input);
console.log('filter in searchFunction:',filter);
table = document.getElementById("Search-Table");
console.log('table in searchFunction:',table);
tr = table.getElementsByTagName("tr");
var innertext = table.getElementsByTagName("tr").innertext;
console.log("innertext :",innertext);
console.log('tr in searchFunction:',tr);
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[2];
console.log('td in for before if:',td);
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
onSort = (column) => (e) => {
const direction = this.state.sort.column ? (this.state.sort.direction === 'asc' ? 'desc' : 'asc') : 'desc';
console.log('direction',direction);
console.log('column',column);
const sortedData = this.state.pageOfItems.sort((a, b) => {
if (column === 'Field1') {
return a.Field1.toUpperCase().localeCompare(b.Field1.toUpperCase());
}
else if (column === 'Last Name') {
return
a.Field1.toUpperCase().localeCompare(b.Field1.toUpperCase());
}
});
if (direction === 'desc') {
sortedData.reverse();
}
this.setState({
pageOfItems: sortedData,
sort: {
direction,
column,
}
});
};
setArrow = (column,className) => {
let current_className = className;
if (this.state.sort.column === column) {
current_className += this.state.sort.direction === 'asc' ? ' asc' : ' desc';
}
console.log(current_className);
return current_className;
};
render() {
var {custID} = this.state;
return (
<div id = "id1">
<div className="row">
<div className="col-lg-12">
<PageHeader>Title of The Page </PageHeader>
</div>
</div>
<form onSubmit={this.handleSubmit}>
<table>
<tr>
<td>
<FormGroup style={spacing}>
<ControlLabel>Field1</ControlLabel>
<FormControl componentClass="select" id="brand" name="brand" placeholder="select">
<option value="Value1">Value1</option>
<option value="Value2">Value2</option>
<option value="Value3">Value3</option>
</FormControl>
</FormGroup>
</td>
<td>
<FormGroup style={spacing}>
<ControlLabel>Field2</ControlLabel>
<FormControl
id="customerId" name="customerId"
type="text"
placeholder="Enter Text"
/>
</FormGroup>
</td>
<td>
<FormGroup style={spacing}>
<ControlLabel>Field3</ControlLabel>
<FormControl
style={spacing}
id="lastname" name="lastname"
type="text"
placeholder="Enter Text"
/>
</FormGroup>
</td>
</tr>
<tr>
<td>
<FormGroup style={spacing}>
<ControlLabel>Field4</ControlLabel>
<FormControl
id="firstName" name="firstName"
type="text"
placeholder="Enter Text"
/>
</FormGroup>
</td>
<td>
<FormGroup style={spacing}>
<ControlLabel>Field5</ControlLabel>
<FormControl
id="housenumber" name="housenumber"
type="text"
placeholder="Enter Text"
/>
</FormGroup>
</td>
<td>
<FormGroup style={spacing}>
<ControlLabel>Field6</ControlLabel>
<FormControl
id="addressline" name="addressline"
type="text"
placeholder="Enter Text"
/>
</FormGroup>
</td>
</tr>
<tr>
<td>
<FormGroup style={spacing}>
<ControlLabel>Field7</ControlLabel>
<FormControl
id="zipcode" name="zipcode"
type="text"
placeholder="Enter Text"
/>
</FormGroup>
</td>
<td>
<FormGroup style={spacing}>
<ControlLabel>Field8</ControlLabel>
<FormControl
id="email" name="email"
type="text"
placeholder="Enter Text"
/>
</FormGroup>
</td>
<td>
<FormGroup style={spacing}>
<ControlLabel>Field9</ControlLabel>
<FormControl
id="phonenumber" name="phonenumber"
type="text"
placeholder="Enter Text"
/>
</FormGroup>
</td>
</tr>
<tr>
<td>
<FormGroup style={spacing}>
<ControlLabel>Field10</ControlLabel>
<FormControl
id="last4digitsphone" name="last4digitsphone"
type="text"
placeholder="Enter Text"
/>
</FormGroup>
</td>
<td></td>
<td>
<FormGroup style={buttonalignment}>
<Button bsStyle="primary" type="submit">Search </Button>
{' '}
<Button bsStyle="primary" type="reset">Clear </Button>
</FormGroup>
</td>
</tr>
</table>
<div className="row ng-scope">
<div className="col-lg-15">
<Panel header={<span> Search Results</span>} >
<div id="dataTables-example_filter" className="dataTables_filter">
<label htmlFor={'search'}>Search:
<input
type="text"
className="form-control input-sm"
placeholder=""
aria-controls="dataTables-example"
id="search" onKeyUp={this.searchFunction}
/>
</label>
</div><br></br>
<div id ="Search-Table" className="table-responsive">
<table className="table table-striped table-bordered table-hover dataTable no-footer" id="dataTables-example" role="grid" aria-describedby="dataTables-example_info">
<thead>
<tr role="row">
<th>Field1</th>
<th>Field2</th>
<th className="sorting" onClick={this.onSort('Field 3','asc')} aria-sort="ascending"
aria-label="Rendering engine: activate to sort column descending"
aria-controls="dataTables-example"
rowSpan="1"
colSpan="1"
tabIndex="0">Field3<span className={this.setArrow('First Name')}></span></th>
<th className="sorting" onClick={this.onSort('Field 4','asc')}>Last Name <span className={this.setArrow('Field 4')}></span></th>
<th>Field3</th>
<th>Field4</th>
<th>Field5</th>
<th>Field6</th>
<th>Field7</th>
<th>Field8</th>
<th>Field9</th>
</tr>
</thead>
<tbody>
{this.state.pageOfItems.map((item, i) => {
return (
<tr key={i} onClick={()=>this.handleClick(item.Field1,item.Field2)}>
<td >{item.Field1}</td>
<td> {item.Field2}</td>
<td> {item.Field3}</td>
<td> {item.Field4}</td>
<td> {item.Field5}</td>
<td> {item.Field6}</td>
<td> {item.Field7}</td>
<td> {item.Field8}</td>
<td> {item.Field9}</td>
<td> {item.Field10}</td>
<td> {item.Field11}</td>
</tr>
);
})}
</tbody>
</table>
<div className="col-sm-6 pullRight " >
<JwPagination items={this.state.newData} onChangePage={this.onChangePage} />
</div>
</div>
</Panel>
</div>
</div>
</form>
<DisplayDetails respData={this.state.respData}/>
</div>
);
}
}
export default displayBlank;
DisplayDetails.js
import React, { PropTypes , Component } from 'react';
class displayDetails extends Component {
render() {
return <h1 >Hello World!</h1>
{this.props.respData.map((item, i) => {
return (
<tr key={i} >
<td >{item.FIELD1}</td>
<td> {item.FIELD2}</td>
</tr>
);
})}
<div className="col-lg-6">
<Panel header={<span>add</span>} >
<div className="table-responsive">
<table className="table table-striped table-bordered table-hover">
<thead>
<tr>
<th> FIELD 1 </th>
<th> FIELD 2 </th>
<th> FIELD 3 </th>
<th> FIELD 4</th>
<th> FIELD 5 </th>
<th> FIELD 6</th>
</tr>
</thead>
<tbody>
{Object.keys(addData).map((item, i) => {
return (
<tr key={i}>
<td> {addData[item].FIELD1}</td>
<td> {addData[item].FIELD2}</td>
<td> {addData[item].FIELD3}</td>
<td> {addData[item].FIELD4}</td>
<td> {addData[item].FIELD5}</td>
<td> {addData[item].FIELD6}</td>
</tr>
);
})}
</tbody>
</table>
</div>
</Panel>
</div>
}
}
export default displayDetails;
class Phone extends React.Component {
constructor(props) {
super(props);
// this.state.phones = [];
this.state = {};
this.state.filterText = "";
this.state.phones = [
{
id: 1,
Field1: '',
Field2: '',
Field3: '',
Field4: '',
Field5: ''
}
];
}
handleUserInput(filterText) {
this.setState({filterText: filterText});
};
handleRowDel(phone) {
var index = this.state.phones.indexOf(phone);
this.state.phones.splice(index, 1);
this.setState(this.state.phones);
};
handleAddEvent(evt) {
var id = (+ new Date() + Math.floor(Math.random() * 999999)).toString(36);
var phone = {
id: id,
Phone_Number: '',
Type: '',
Receive_Calls: '',
Receive_Texts: '',
Preferred_Phone_Number: ''
}
this.state.phones.push(phone);
this.setState(this.state.phones);
}
handlephoneTable(evt) {
var item = {
id: evt.target.id,
name: evt.target.name,
value: evt.target.value
};
console.log('item.value in phone',item.value);
var phones = this.state.phones.slice();
var newphones = phones.map(function(phone) {
for (var key in phone) {
if (key == item.name && phone.id == item.id) {
phone[key] = item.value;
}
}
return phone;
});
this.setState({phones:newphones});
// console.log(this.state.phones);
};
render() {
return (
<div>
<PhoneTable onphoneTableUpdate={this.handlephoneTable.bind(this)} onRowAdd={this.handleAddEvent.bind(this)} onRowDel={this.handleRowDel.bind(this)} phones={this.state.phones} filterText={this.state.filterText}/>
</div>
);
}
}
class PhoneTable extends React.Component {
render() {
var onphoneTableUpdate = this.props.onphoneTableUpdate;
var rowDel = this.props.onRowDel;
var filterText = this.props.filterText;
var phone = this.props.phones.map(function(phone) {
if (phone.Type.indexOf(filterText) === -1) {
return;
}
return (<PhoneRow onphoneTableUpdate={onphoneTableUpdate} phone={phone} onDelEvent={rowDel.bind(this)} key={phone.id}/>)
});
return (
<div>
<th>Phone</th>
<button type="button" onClick={this.props.onRowAdd} className="btn btn-success pull-right">Add</button>
<table className="table table-bordered">
<thead>
<tr>
<th>Phone_Number</th>
<th>Type</th>
<th>Receive_Calls</th>
<th>Receive_Texts</th>
<th>Preferred_Phone_Number</th>
</tr>
</thead>
<tbody>
{phone}
</tbody>
</table>
</div>
);
}
}
class PhoneRow extends React.Component {
onDelEvent() {
this.props.onDelEvent(this.props.phone);
}
render() {
return (
<tr className="eachRow">
<EditableCell onphoneTableUpdate={this.props.onphoneTableUpdate} cellData={{
"type": "Field1",
value: this.props.phone.Field1,
id: this.props.phone.id
}}/>
<EditableCell onphoneTableUpdate={this.props.onphoneTableUpdate} cellData={{
type: "Field2",
value: this.props.phone.Field2,
id: this.props.phone.id
}}/>
<EditableCell onphoneTableUpdate={this.props.onphoneTableUpdate} cellData={{
type: "Field3",
value: this.props.phone.Field3,
id: this.props.phone.id
}}/>
<EditableCell onphoneTableUpdate={this.props.onphoneTableUpdate} cellData={{
type: "Field4",
value: this.props.phone.Field4,
id: this.props.phone.id
}}/>
<EditableCell onphoneTableUpdate={this.props.onphoneTableUpdate} cellData={{
type: "Field5",
value: this.props.phone.Field5,
id: this.props.phone.id
}}/>
<td className="del-cell">
<input type="button" onClick={this.onDelEvent.bind(this)} value="REMOVE" className="del-btn"/>
</td>
</tr>
);
}
}
class EditableCell extends React.Component {
render() {
return (
<td>
<input type='text' name={this.props.cellData.type} id={this.props.cellData.id} value={this.props.cellData.value} onChange={this.props.onphoneTableUpdate}/>
</td>
);
}
}
export default Phone;
You may use context to pass your props. Here is the link of official documentation.
Context is designed to share data that can be considered “global” for a tree of React components.

How can I get the value from select option from Meteor/React?

I have implemented the webapp by Meteor/React with some functions.
Then I have one function which I need the value from select option.
I see some example to use setState. But the code I used is different.
I try to use some functions/ways but I cannot get the update value.
In this code I use day1Changed function to process select value to update.
Please help me to get the value from select from the following code:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { Table, Alert, Button, FormGroup, FormControl } from 'react-bootstrap';
import { Meteor } from 'meteor/meteor';
import { createContainer } from 'meteor/react-meteor-data';
import { Registers } from '../../api/registers';
const handleRemove = (registerId) => {
if (confirm('Are you sure? This is permanent!')) {
Meteor.call('registers.remove', registerId, (error) => {
if (error) {
console.log(error.reason, 'danger');
} else {
console.log('success');
}
});
}
};
const toggleChecked = (registerId, paid) => {
Meteor.call('registers.setChecked', registerId, !paid);
}
const day1Changed = (registerId) => {
console.log(this.day1.value);
Meteor.call('registers.day1Changed', registerId, this.day1.value);
}
const DSRegisters = ({ registers, totalCount, match, history }) => (
<div className="Registers">
<div className="page-header clearfix">
<br />
<br />
<h4 className="pull-left">Registration </h4> <h4>All user {totalCount} </h4>
<br />
<br />
<Link className="btn btn-success" to={`${match.url}/upload`}>Upload User</Link>
<Link className="btn btn-success pull-right" to={`${match.url}/new`}>Add</Link>
</div>
{registers.length ? <Table striped responsive>
<thead>
<tr>
<th>Item</th>
<th>Salution</th>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>Age</th>
<th>Province</th>
<th>Bhumdharm</th>
<th>Amount</th>
<th>Paid</th>
<th>15/9/60</th>
<th>16/9/60</th>
<th>17/9/60</th>
<th>Accommodation</th>
<th>Remark</th>
<th>Updated</th>
<th>Created</th>
<th>User</th>
<th />
<th />
</tr>
</thead>
<tbody>
{registers.map(({ _id, gender, salution, firstname, lastname, province, bhumdharmlevel, age, amount, paid, day1, day2, day3, accommodation, remark, username, createdAt, updatedAt }, index) => (
<tr key={_id}>
<td>{index+1}</td>
<td>{salution}</td>
<td>{firstname}</td>
<td>{lastname}</td>
<td>{gender}</td>
<td>{age}</td>
<td>{province}</td>
<td>{bhumdharmlevel}</td>
<td>{amount}</td>
<td>
<input
type="checkbox"
readOnly
checked={paid}
onClick={() => toggleChecked(_id,paid)}
/>
</td>
<td>
<FormGroup>
<FormControl
componentClass="select"
name="day1"
inputRef={day1 => (this.day1 = day1)}
defaultValue={day1}
onChange={() => day1Changed(_id, day1)}>
<option value=""></option>
<option value="leave">Leave</option>
<option value="come">Come</option>
<option value="absense">Absense</option>
</FormControl>
</FormGroup>
</td>
<td>{day2}</td>
<td>{day3}</td>
<td>{accommodation}</td>
<td>{remark}</td>
<td>{updatedAt.getDate()}/{updatedAt.getMonth()+1}/{updatedAt.getFullYear()+543} {updatedAt.getHours()}:{(updatedAt.getMinutes()<10?'0':'')+updatedAt.getMinutes()}</td>
<td>{createdAt.getDate()}/{createdAt.getMonth()+1}/{createdAt.getFullYear()+543}</td>
<td>{username}</td>
<td>
<Button
bsStyle="primary"
onClick={() => history.push(`${match.url}/${_id}/edit`)}
block
>Edit</Button>
</td>
<td>
<Button
bsStyle="danger"
onClick={() => handleRemove(_id)}
block
>Delete</Button>
</td>
</tr>
))}
</tbody>
</Table> : <Alert bsStyle="warning">Nobody yet!</Alert>}
</div>
);
DSRegisters.propTypes = {
regs: PropTypes.object,
registers: PropTypes.arrayOf(PropTypes.object).isRequired,
totalCount: PropTypes.number.isRequired,
match: PropTypes.object.isRequired,
history: PropTypes.object.isRequired,
};
export default createContainer(() => {
const subscription = Meteor.subscribe('registers');
return {
registers: Registers.find({}, { sort: { createdAt: 1 } }).fetch(),
totalCount: Registers.find({}).count(),
};
}, DSRegisters);
You can get the value from a select option like snippet bellow:
handleChange(name, e) {
this.setState([name]: e.target.value)
}
<select className="ui dropdown" onClick={this.handleChange.bind(this, 'STATE_NAME_HERE')}>
<option value="1">Male</option>
</select>
This code works with Meteor-React-SemanticUi

Categories

Resources