Multiple handle change - javascript

i am working on project which contains more than 200 input fields for list.is it possible to manage them with single state input
import { useState } from "react";
import Item from "../Components/Item";
const initialState={
input:''
}
const List = () => {
const [values,setValues]=useState(initialState)
const handleChange=(e)=>{
setValues({
...values,[e.target.name]:e.target.value
})
}
return (
<div className="container">
<div className="listhead">
<h3 className="text-center">Price List-2022</h3>
<table className="table table-bordered border-dark table-hover text-center">
<thead className="bg-success text-white table-bordered border-dark">
<tr>
<th>S.No</th>
<th>Item</th>
<th>Price</th>
<th>Qty</th>
<th>Total</th>
</tr>
</thead>
<Item
product="bomb"
name="input"
price="50"
value={values.input}
handleChange={handleChange}
/>
<Item
product="chakkar"
name="input"
price="100"
value={values.input}
handleChange={handleChange}
/>
</table>
</div>
</div>
);
};
export default List;
child element
const Item = ({name,product,price,value,handleChange}) => {
return (
<tbody>
<tr>
<th>1</th>
<th>{product}</th>
<th>{price}</th>
<th className="w-25">
<input
name={name}
value={value}
onChange={handleChange}
type='number'
/>
</th>
<th> </th>
</tr>
</tbody>
);
};
export default Item;
with this code if i enter values in input fields all other input fields reads the same value. if i need to create 200 input field with data, what are the ways to do that?

You can pass all values to item
like this :
<Item
name="input"
price="50"
value={values}
handleChange={handleChange}
/>
and in Item component set props of input like this :
<input
name={name}
value={values[name]}
onChange={handleChange}
type='number'
/>

Your inputs have the same name, if you want to set the state for the different inputs you'll need a unique identifier.
This way you can use the e.target.name as a key in your state object.
<Item
product="Something"
name={"unique identifier"}
price="50"
value={values["unique identifier"]}
handleChange={handleChange}
/>
A good practice is also to use the callback function with the useState to make sure you have the most recent values.
setValues((prevValues) => {
return {
...prevValues,
[e.target.name]: e.target.value,
};
});
``

Related

× TypeError: Cannot read properties of undefined (reading 'form')

I am trying to trigger the handleSubmit function for the form but getting the error mentioned in the title. Adding the code for the handle submit function as well as the form below. Please help out
I am using a react template from CoreUI for this so most tags are from that. The form will be nested under the CCard Tag and the submit button is in the Card footer. I have the form in a separate component and i am storing the values in the state which are to be passed to the post api call on submit which is inside the handle submit function
const DataSources = () => {
const [collapsed, setCollapsed] = React.useState(true)
const [showElements, setShowElements] = React.useState(true)
const entryList = []
const [tableEntries, setTableEntries] = React.useState(entryList)
function handleSubmit(){
// POST request using axios with set headers
const article = { "connectionType":"InstagramConnection","id":"e5ee8320-a307-448b-a0ed-0829a187050f","name":this.state.value,"accessCredentials":{"id":2,"token":this.state.access_token} };
const headers = {
"Content-Type": "application/json; charset=utf-8"
};
Axios.post('http://localhost:8080/api/connections', article, { headers })
.then(response => console.log(response.data.id));
};
useEffect(() => {
Axios.get('http://localhost:8080/api/connections')
.then(res => {
console.log(res.data);
const newList = entryList.concat(res.data);
Array.prototype.forEach.call(res.data, response => {
setTableEntries(prevTableEntries => [...prevTableEntries,response]);
});
console.log(tableEntries);
})
.catch(err => console.log(err));
}, []);
return (
<>
<CRow>
<CCol xs="12" md="10">
<p className="h1">Data Sources</p>
</CCol>
<CCol xs="12" md="2">
<CDropdown className="m-1" size="lg" align="center" size="lg">
<CDropdownToggle color="secondary">
Select Client
</CDropdownToggle>
<CDropdownMenu>
<CDropdownItem>Client 1</CDropdownItem>
<CDropdownItem>Client 2</CDropdownItem>
</CDropdownMenu>
</CDropdown>
</CCol>
</CRow>
<br></br>
<CRow>
<CCol xs="12" md="4">
<CCard>
<CCardHeader>
Add Data Source
</CCardHeader>
<CCardBody>
<CForm ref={ (ref) => { this.form = ref; } } className="form-horizontal" onSubmit={handleSubmit}>
<CFormGroup>
<Facebook />
</CFormGroup>
</CForm>
</CCardBody>
<CCardFooter>
<CButton type="submit" size="sm" color="primary" value="Submit" onClick={ () => { this.form.dispatchEvent(new Event('submit')) } }><CIcon name="cil-scrubber" /> Add Connection</CButton>
<CButton type="reset" size="sm" color="danger"><CIcon name="cil-ban" /> Reset</CButton>
</CCardFooter>
</CCard>
</CCol>
<CCol xs="12" md="8">
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Id</th>
<th scope="col">App Name</th>
<th scope="col">Connection Type</th>
<th scope="col">Options</th>
</tr>
</thead>
<tbody>
{tableEntries.map((item) => (
<>
<tr>
<th scope="row">1</th>
<td>{item.id}</td>
<td>{item.name}</td>
<td>{item.connectionType}</td>
<td>
<CDropdown className="m-1" size="lg">
<CDropdownToggle color="secondary">
Select Option
</CDropdownToggle>
<CDropdownMenu>
<CDropdownItem>Delete</CDropdownItem>
<CDropdownItem>Reauthorize</CDropdownItem>
</CDropdownMenu>
</CDropdown>
</td>
</tr>
</>
))}
</tbody>
</table>
</CCol>
</CRow>
</>
)
}

How to load data on button click using react

In my below code i have one table and when i select radio button and click on submit button then load the data and show in console. this is fine.
but in my table i have many data in table body. and when i select 1st row radio button then click submit button, then load data and show in console. that is fine. but again i select 2nd row radio button and click submit button, then i am not able to fetch data and show in console. and again i select the 3rd row and select radio button and click submit button then i m getting data in console.like that
why i'm getting like this?
class ProvFileRptSearchResult extends React.Component {
constructor(props) {
super();
this.state = {
pymtDetails:[],
data: [],
rowDetails:[],
checkbox: false
};
// this.handleFile=this.handleFile.bind(this);
this.handleClick=this.handleClick.bind(this);
}
handleClick() {
const apiUrl = "https://mocki.io/v1/b512f8b8-64ab-46e4-9e0c-9db538a0ad9e";
if (this.state.checkbox) {
fetch(apiUrl)
.then((response) => response.json())
.then((data) => {
this.setState({ data: data });
console.log("This is your data", data);
window.open("https://example.com", "_blank");
})
} else {
alert("Data not fetched!");
}
// console.log('click');
}
render()
{
return(
<div>
<div className="table-employee" style={{ marginTop:"20px",border:" 1.5px solid darkgray" }}>
<table className="table table-hover table-bordered table-sm">
<thead>
<tr >
<th scope="col">Select</th>
<th scope="col"> LOAD DATE</th>
<th scope="col"> FILE DATE</th>
<th scope="col"> SERVICE</th>
<th scope="col"> PROVISIONER CODE </th>
<th scope="col"> DESCRIPTION</th>
</tr>
</thead>
<tbody>
{
this.props.customerDetails.map((type,j)=>{
return(
<tr>
<td ><input type="radio" preventDefault name="select" key={j} onClick={(e) =>this.rowSelected(j)} value={this.state.checkbox}
onChange={(e) =>
this.setState({ checkbox: !this.state.checkbox })
}/></td>
<td> {type.provis_file_stamp}</td>
<td> {type.provis_file_hdrdt}</td>
<td> {type.service_code}</td>
<td>{type.provisioner_code}</td>
<td>{type.provisioner_desc}</td>
</tr>
)
})
}
</tbody>
</table>
</div>
<div className="btn-submit" >
<button className="btn btn-primary" style={{marginRight:"30px"}} type="submit" onClick={this.handleClick}>FILE</button>
</div>
</div>
)
}
what you are doing is, you are handling the data using single state variable.
take three separate variables for all your radio buttons
and handle them separately
you need some changes in checkbox value and input tags values and setstate,you can find the changes. below is the code that works:
import React from "react";
import ReactDOM from "react-dom";
class Test extends React.Component {
constructor(props) {
super();
this.state = {
data: [],
checkbox: 0
};
}
handleClick = () => {
const apiUrl = "https://mocki.io/v1/b512f8b8-64ab-46e4-9e0c-9db538a0ad9e";
if (this.state.checkbox) {
fetch(apiUrl)
.then((response) => response.json())
.then((data) => {
this.setState({ data: data });
console.log("This is your data", data);
window.open("https://example.com", "_blank");
});
} else {
alert("not load data!");
}
};
render() {
return (
<div>
<div
className="table-employee"
style={{ marginTop: "20px", border: " 1.5px solid darkgray" }}
>
<table className="table table-hover table-bordered table-sm">
<thead>
<tr>
<th scope="col">Select</th>
<th scope="col"> LOAD DATE</th>
<th scope="col"> FILE DATE</th>
<th scope="col"> SERVICE</th>
<th scope="col"> PROVISIONER CODE </th>
<th scope="col"> DESCRIPTION</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input
value={this.state.checbox === 1 ? true : false}
onChange={(e) => this.setState({ checkbox: 1 })}
type="radio"
preventDefault
name="select"
/>
</td>
<td>dfgrty</td>
<td>fgfg</td>
<td>fgfg</td>
<td>erer</td>
<td>uuio</td>
</tr>
<tr>
<td>
<input
value={this.state.checbox === 2 ? true : false}
onChange={(e) => this.setState({ checkbox: 2 })}
type="radio"
preventDefault
name="select"
/>
</td>
<td>dfgrty</td>
<td>fgfg</td>
<td>fgfg</td>
<td>erer</td>
<td>uuio</td>
</tr>
<tr>
<td>
<input
value={this.state.checbox === 1 ? true : false}
onChange={(e) => this.setState({ checkbox: 3 })}
type="radio"
preventDefault
name="select"
/>
</td>
<td>dfgrty</td>
<td>fgfg</td>
<td>fgfg</td>
<td>erer</td>
<td>uuio</td>
</tr>
</tbody>
</table>
</div>
<div className="btn-submit">
<button
className="btn btn-primary"
style={{ marginRight: "30px" }}
type="submit"
onClick={this.handleClick}
>
submit
</button>
</div>
</div>
);
}
}
ReactDOM.render(<Test />, document.getElementById("root"));
// https://mocki.io/v1/b512f8b8-64ab-46e4-9e0c-9db538a0ad9e
// http://codeskulptor-assets.commondatastorage.googleapis.com/assets_clock_minute_arrow.png

React : Search bar capturing key but not showing data

I'm a complete beginner. I have the following React component where I need to display a table with data and perform a search on it using a generated API using Laravel as backend.
Displaying data works great, searching data directly from the API link works, but when trying to perform the search on the table, all the data that was showing disappears and no result is displaying.
If it can help, in chrome's console when typing I have the following
SyntheticEvent {dispatchConfig: {…}, _targetInst: FiberNode, nativeEvent: InputEvent, type: "change", target: input.form-control, …}
SyntheticEvent {dispatchConfig: {…}, _targetInst: FiberNode, _dispatchInstances: FiberNode, nativeEvent: InputEvent, _dispatchListeners: ƒ, …}
I believe I have a problem in handleSearchChange
class Patient extends React.Component {
constructor(props) {
super(props)
this.state = {
patients : [],
};
this.handleSearchChange = this.handleSearchChange.bind(this);
}
// Problem in this one
handleSearchChange(key){
console.log(key);
fetch("api/patients/search?q="+key)
.then(response => {
this.setState({
patients:[]
});
})
}
componentDidMount() {
axios.get('api/patients')
.then(response => {
this.setState({
patients: response.data})
})
.catch(err => console.log(err));
}
render() {
return (
<div>
<Container>
<div>
<input
type="text"
className="form-control"
placeholder="Search..."
onChange= onChange={this.handleSearchChange}
/>
</div>
<Table>
<Thead>
<Tr>
<Th>ID</Th>
<Th>FIRST NAME</Th>
<Th>LAST NAME</Th>
</Tr>
</Thead>
<Tbody>
{this.state.patients.reverse().map((patient) => (
<Tr>
<Td>
{patient.id}
</Td>
<Td>
{patient.firstname}
</Td>
<Td>
{patient.lastname}
</Td>
</Tr>
))}
</Tbody>
</Table>
</Container>
</div>
);
}
}
export default Patient;
It's the problem with your input
<input
type="text"
className="form-control"
placeholder="Search..."
onChange= onChange={this.handleSearchChange}
/>
You need to capture onChange event from input, get the value then send it to handleSearchChange function, like this:
<input
type="text"
className="form-control"
placeholder="Search..."
onChange={e => this.handleSearchChange(e.target.value)}
/>
You might question why e.target.value, it's the event object, you can console.log it to see more detail.
Edit: in handleSearchChange function, you also need to setState the patients gotten from response,just like what you did in componentDidMount method

if ternario does not work, function has value but never used says

I am new with programing and I want to use if ternario, but it doesn't work. I have two functions and I create a third function to show one of them or the other. It is an application in ReactJS. Below is the code:
import { Table } from "react-bootstrap";
import { Link } from "react-router-dom";
import { useCartContext } from "../../Context/CartContext";
const emptyCart = () => {
return(
<>
<div>
<h3>The Cart is empty</h3>
<p>
Return to home to see our products
</p>
<Link to='/' ><button className="btn btn-info"> Home </button></Link>
</div>
</>
);
};
const CartFunction = () => {
const { list, totalPrice } = useCartContext();
return (
<Table striped hover>
<thead>
<tr>
<th>Product</th>
<th>Title</th>
<th>Quantity</th>
<th>Price</th>
</tr>
</thead>
<tbody>
{list.map((varietal) => (
<tr key={varietal.id}>
<td>
<img
src={varietal.pictureUrl}
alt='img'
style={{ width: "82px" }}
/>
</td>
<td>{varietal.title}</td>
<td>{varietal.count}</td>
<td>${varietal.price}</td>
</tr>
))}
</tbody>
<thead>
<tr>
<td colSpan="3">Total</td>
<td>${totalPrice()}</td>
</tr>
</thead>
</Table>
);
};
const CartComponent = () => {
const { list } = useCartContext();
return (
<>
{list.length !== 0 ? <CartFunction /> : <emptyCart />}
</>
);
};
export default CartComponent;
Visual Code it says that emptyCard has a value but it is never used. If there is someone that could help me I would appreciate it. Cheers

How can i display key value pairs in a table grid in react js.?

I'm trying to display key-value pairs in react js,
but somehow I cannot display them properly. I have created a table widget and I am not getting the right display
My table Widget
import React from "react";
function Table(props) {
const { tablevalue } = props;
console.log(tablevalue);
return (
<div className="table">
<table className="table table-hover">
<tbody>
{tablevalue.map((item, value) =>
Object.entries(item, (key, value) => {
return (
<tr className="table-row">
<th scope="col" key={`tablevalue-${key}`}>
{key}
</th>
<td key={`tablevalue-${value}`}>{value}</td>
</tr>
);
})
)}
</tbody>
</table>
</div>
);
}
export default Table;
app.js
import React, { Fragment } from "react";
import Dropdown from './components/widgets/Dropdown/index'
import Table from './components/widgets/Table/index'
function DropdownTest() {
return (
<h3>
<b>Profit</b>
</h3>
<br />
<Table
tablevalue = {[{key:'Binance' , value: 'Polonix'}, {key:'Profit' , value:'Loss'}]}
/>
</div>
);
}
export default DropdownTest;
My output
Whereas I want my output to be displayed in terms of table
You can use table header
<tbody>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
{tablevalue.map(({ key, value }) => (
<tr className="table-row">
<td key={`tablevalue-${key}`}>{key}</td>
<td key={`tablevalue-${value}`}>{value}</td>
</tr>
))}
</tbody>
Code
const Table = ({ tablevalue }) => (
<div className="table">
<table className="table table-hover">
<tbody>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
{tablevalue.map(({ key, value }) => (
<tr className="table-row">
<td key={`tablevalue-${key}`}>{key}</td>
<td key={`tablevalue-${value}`}>{value}</td>
</tr>
))}
</tbody>
</table>
</div>
);
const DropdownTest = () => (
<div>
<h3>
<b>Profit</b>
</h3>
<br />
<Table
tablevalue={[
{ key: "Binance", value: "Polonix" },
{ key: "Profit", value: "Loss" }
]}
/>
</div>
);
ReactDOM.render(
<React.StrictMode>
<DropdownTest />
</React.StrictMode>,
document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
I've not seen Object.entries used this way. I would usually use a forEach on it:
Object.entries(item).forEach(entry => {
let key = entry[0];
let value = entry[1];
});
Though a little bit more performant would be using a for in instead, as Object.entries creates a brand new array then forEach iterates through that, which is unnecessary:
for (const key in item) {
let value = obj[key];
}
You can do it this way:
import React from "react";
export default props => {
console.log(props.tablevalue);
const ths = props.tablevalue.map(({ key, value }) => (
<th key={value}>{key}</th>
));
const values = props.tablevalue.map(obj => <td>{obj.value}</td>);
return (
<>
<table>
<tr>{ths}</tr>
<tr>{values}</tr>
</table>
</>
);
};
Here's a stackblitz that displays the table.
Ultimately it all comes down to how you want that table to be displayed, you can tweak some things as you want.
I think you have to create a header separately. and after that loop thought the data and apply css for table row. please find the below code.
import React from 'react';
import './index.css';
function Table(props) {
const {
tablevalue,
} = props
console.log(tablevalue)
return (
<div className="table">
<table className="table table-hover">
<tbody>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
{tablevalue.map((item, value) => {
return (
<tr className="table-row">
<td key={`tablevalue-${value}`}>{item.key}</td>
<td key={`tablevalue-${value}`}>{item.value}</td>
</tr>
)
})}
</tbody>
</table>
</div>
)
}
export default Table;
Check this sandbox: https://codesandbox.io/s/goofy-breeze-fdcdr
Object.keys(tablevalue[0]).map((key) => {key}). You can use this in header tr and loop over it then
Change the Table component to something like this:
import React from "react";
function Table(props) {
const { tablevalue } = props;
return (
<div className="table">
<table className="table table-hover">
<tbody>
<tr>
{Object.keys(tablevalue[0]).map(key => (
<th key={key}>{key}</th>
))}
</tr>
{tablevalue.map(({ key, value }) => (
<tr className="table-row" key={`tablevalue-${key}`}>
<td>{key}</td>
<td>{value}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default Table;

Categories

Resources