React Hooks Antd props to update - reactjs

I`m trying to pass the data from a table component to a form that opens when I press the edit button, I know how to do it with react Class but I'm trying with hooks but I still don't understand how to do it.
Here is an image of the table.
Here is an image of the form.
Index.js
const GestionUsuarios = () => {
const [data, setData] = React.useState([]);
const [loading, setLoading] = React.useState(false);
const [form] = Form.useForm();
const [visible, setVisible] = useState(false);
const [visibleEdit, setVisibleEdit] = useState(false);
const [users, setUsers] = useState(null);
const [post, setPost] = React.useState(null);
const [searchText, setSearchText] = useState('');
const [searchedColumn, setSearchedColumn] = useState('');
const columns = [
{
title: 'ID',
dataIndex: 'id',
sorter: true,
key: 'id',
//render: name => `${name.first} ${name.last}`,
//width: '20%',
},
{
title: 'Tipo de usuario',
dataIndex: 'tipo',
filters: [
{ text: 'Administrador', value: '1' },
{ text: 'Supervisor', value: 'super' },
{ text: 'Expedicion Granulado', value: 'expg' },
{ text: 'Expedicion Silo', value: 'exps' },
{ text: 'Lectura', value: 'lectura' },
],
},
{
title: 'Nombre',
dataIndex: 'nombre',
},
{
title: 'Apellido',
dataIndex: 'apellido',
},
{
title: 'Alias',
dataIndex: 'username',
},
{
title: 'Email',
dataIndex: 'email',
},
{
title: 'Action',
key: 'action',
fixed: 'right',
width: 100,
render: (_, record) => (
<div>
<Button
//onClick={() => retrieveConfig(record.id)}
onClick={() => {
setVisibleEdit(true);
}}
icon={<EditOutlined />}
/>
</div>
),
},
{
title: '',
key: 'action2',
fixed: 'right',
width: 100,
render: (_, record) => (
<Button
//onClick={() => deleteConfig(record.id, record.test_type)}
onClick={() => deleteRoute(record.id)}
icon={<DeleteOutlined />}
/>
),
},
];
useEffect(() => {
fetch('http://localhost:8080/api/usuarios', {
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
}).then((res) =>
res.json().then((result) => {
setUsers(result);
console.log(result);
})
);
}, []);
const onEdit = (response, id) => {
console.log('USUARIO A editar: ', response);
setVisible(false);
axios
.put(`http://localhost:8080/api/usuarios/${id}`, {
tipo: response.tipo,
nombre: response.nombre,
pass: response.pass,
username: response.username,
apellido: response.apellido,
email: response.email,
})
.then((response) => {
setPost(response.data);
window.location.reload();
});
};
return (
<div>
<Button
onClick={() => {
setVisible(true);
}}
type='primary'
style={{ marginBottom: 16 }}
>
Nuevo usuario
</Button>
<AddForm
visible={visible}
onCreate={onCreate}
onCancel={() => {
setVisible(false);
}}
/>
<EditForm
visible={visibleEdit}
onCreate={onCreate}
onCancel={() => {
setVisibleEdit(false);
}}
/>
<Table
columns={columns}
dataSource={users}
pagination={pagination}
loading={loading}
rowKey={(record) => record.id}
//onChange={this.handleTableChange}
//rowKey="id"
/>
</div>
);
};
export default GestionUsuarios;
EditForm.js
const EditFormUsuarios = ({ visible, onCreate, onCancel, props }) => {
const [form] = Form.useForm();
const [post, setPost] = React.useState(null);
const [userID, setUserID] = useState(null);
const [username, setUsername] = useState('');
const [dataform, setDatosForm] = useState({
id: '',
tipo: '',
nombre: '',
apellido: '',
username: '',
pass: '',
email: '',
});
const handleUserId = (id) => {
console.log('ID seleccionado: ', id);
//setVisible(false);
axios
.get(`http://localhost:8080/api/usuarios/${id}`, {
//.then(response => response.json())
})
.then((result) => {
setUserID(result);
console.log(result);
axios.put(`http://localhost:8080/api/usuarios/${result.id}`, {
tipo: result.tipo,
nombre: result.nombre,
apellido: result.apellido,
username: result.username,
pass: result.pass,
email: result.email,
//.then(response => response.json())
});
});
};
useEffect(() => {
/*if(this.props.item){
const { tipo} = this.props.item
this.setState({ tipo})
}
if(this.props.item){
const { nombre} = this.props.item
this.setState({ nombre})
}
if(this.props.item){
const { apellido} = this.props.item
this.setState({ apellido})
}
if(this.props.item){
const { username} = this.props.item
this.setState({ username})
}
if(this.props.item){
const { pass} = this.props.item
this.setState({ pass})
}
if(this.props.item){
const { email} = this.props.item
this.setState({ email})
}*/
}, []);
return (
<Modal
{...props}
visible={visible}
title='Editar usuario'
okText='Confirmar'
cancelText='Cancelar'
onCancel={onCancel}
onOk={() => {
form
.validateFields()
.then((values) => {
form.resetFields();
onCreate(values);
})
.catch((info) => {
console.log('Validate Failed:', info);
});
}}
>
<Form
form={form}
layout='vertical'
name='form_in_modal'
initialValues={{
modifier: 'public',
}}
>
<Form.Item
name='id'
label='Alias'
rules={[
{
required: true,
message: 'Introduce el alias',
},
]}
// onChange={e => setUsername(e.target.value)}
value={dataform && dataform.id}
></Form.Item>
<Form.Item
name='username'
label='Alias'
rules={[
{
required: true,
message: 'Introduce el alias',
},
]}
onChange={(e) => setUsername(e.target.value)}
value={dataform && dataform.username}
>
<Input />
</Form.Item>
<Form.Item
name='pass'
label='Contraseña'
rules={[
{
required: true,
message: 'Introduce la contraseña',
},
]}
>
<Input />
</Form.Item>
<Form.Item
name='nombre'
label='Nombre'
rules={[
{
required: true,
message: 'Introduce el nombre',
},
]}
>
<Input />
</Form.Item>
<Form.Item
name='apellido'
label='Apellido'
rules={[
{
required: true,
message: 'Introduce el apellido',
},
]}
>
<Input />
</Form.Item>
<Form.Item
name='email'
label='Email'
rules={[
{
required: true,
message: 'Introduce el email',
},
]}
>
<Input />
</Form.Item>
<Form.Item
name='tipo'
label='Tipo de usuario'
rules={[
{
required: true,
message: 'Introduce el tipo de usuario!',
},
]}
>
<Input />
</Form.Item>
</Form>
</Modal>
);
};
export default EditFormUsuarios;

from index.js ===> onCreate={onCreate} ?? add the onEdit or related event handling function

Related

How to change value in GooglePlacesAutocomplete

How I can change value from this GooglePlacesAutocomplete?!
I want change googleplacesautocomplete value when I change marker position on map.
I have the opportunity to use only this package.
Maybe you can somehow change the value without using something third-party from the packages.
I've this code.
<Form.Item name="address">
<GooglePlacesAutocomplete
apiKey={API}
apiOptions={{
language: "ua",
region: "ua",
}}
selectProps={{
value,
onChange: setValue,
placeholder: "Select your address",
}}
name="address"
value={value.label}
/>
</Form.Item>
Full code:
import React, { useState, useCallback, useEffect } from "react";
import { GoogleMap, Marker, useJsApiLoader } from "#react-google-maps/api";
import { API } from "../../constants/map";
import Header from "../navigation/header";
import { createOffer } from "../../services/offerService";
import { getGoodCategories } from "../../services/goodCategoryService";
import { useHistory } from "react-router-dom";
import { inputValidationErrors } from "../../constants/messages/inputValidationErrors";
import { Form, Input, Button, DatePicker, AutoComplete, Select } from "antd";
import Geocode from "react-geocode";
import GooglePlacesAutocomplete, {
geocodeByAddress,
getLatLng,
} from "react-google-places-autocomplete";
Geocode.setApiKey(API);
Geocode.setLanguage("ua");
Geocode.setRegion("ua");
Geocode.enableDebug();
const { TextArea } = Input;
const { Option } = Select;
const containerStyle = {
width: "100%",
height: "100%",
};
const center = {
lat: 50.643,
lng: 26.263,
};
const defaultOptions = {
panControl: true,
zoomControl: true,
zoomEnabled: true,
mapTypeControl: true,
disableDefaultUI: true,
scaleControle: true,
streetViewControl: true,
rotateControl: true,
clickableIcons: true,
keyboardShortcuts: true,
scrollwheel: true,
fullscreenControl: true,
};
export default function Offer() {
const { isLoaded } = useJsApiLoader({
id: "google-map-script",
googleMapsApiKey: API,
});
let history = useHistory();
const [map, setMap] = useState();
const [clickedLatLng, setClickedLatLng] = useState(center);
const [data, setData] = useState(null);
const [value, setValue] = useState("Rivne");
const [coord, setCoord] = useState({ lat: 0, lng: 0 });
const onLoad = useCallback(function callback(map) {
const bounds = new window.google.maps.LatLngBounds(center);
map.fitBounds(bounds);
setMap(map);
}, []);
const onUnmount = useCallback(function callback(map) {
setMap(null);
}, []);
const [form] = Form.useForm();
const getData = (lat, lng) => {
Geocode.fromLatLng(lat, lng).then(
(response) => {
const address = response.results[0].formatted_address;
let settlement, region;
for (
let i = 0;
i < response.results[0].address_components.length;
i++
) {
for (
let j = 0;
j <
response.results[0].address_components[i].types.length;
j++
) {
switch (
response.results[0].address_components[i].types[j]
) {
case "locality":
settlement =
response.results[0].address_components[i]
.long_name;
break;
case "administrative_area_level_1":
region =
response.results[0].address_components[i]
.long_name;
break;
}
}
}
//setValue(address);
console.log("VALUE", value);
form.setFieldsValue({
address: address,
settlement: settlement,
region: region,
});
},
(error) => {
console.error(error);
}
);
};
useEffect(async () => {
setData(await getGoodCategories());
if (value) {
geocodeByAddress(value.label).then((result) => {
getLatLng(result[0]).then((googleCoord) =>
setCoord(googleCoord)
);
});
}
}, [geocodeByAddress, getLatLng, value, setCoord]);
console.log(coord.lat, coord.lng);
const onFinish = (values) => {
console.log(values);
createOffer(values, clickedLatLng, history);
};
const onFinishFailed = (values) => {
console.log("error");
};
return isLoaded ? (
<>
<Header />
<div className="createOfferBody">
<h1>Create offer</h1>
<Form
form={form}
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
initialValues={{ remember: true }}
onFinish={onFinish}
onFinishFailed={onFinishFailed}
scrollToFirstError
>
<div className="topFormBlock">
<div className="addressBlock">
<Form.Item name="address">
<GooglePlacesAutocomplete
apiKey={API}
apiOptions={{
language: "ua",
region: "ua",
}}
selectProps={{
value,
onChange: setValue,
placeholder: "Select your address",
}}
name="address"
value={value.label}
/>
</Form.Item>
<Form.Item
name="settlement"
rules={[
{
type: "string",
message:
inputValidationErrors.EMPTY_SETTLEMENT_MESSAGE,
},
{
required: true,
message:
inputValidationErrors.EMPTY_SETTLEMENT_MESSAGE,
},
]}
>
<Input
name="settlement"
placeholder="Enter your settlement"
/>
</Form.Item>
<Form.Item
name="region"
rules={[
{
type: "string",
message:
inputValidationErrors.EMPTY_SETTLEMENT_MESSAGE,
},
{
required: true,
message:
inputValidationErrors.EMPTY_SETTLEMENT_MESSAGE,
},
]}
>
<Input
name="region"
placeholder="Enter your settlement"
/>
</Form.Item>
</div>
<div className="mapBlock">
<GoogleMap
mapContainerStyle={containerStyle}
center={center}
onLoad={onLoad}
onUnmount={onUnmount}
options={defaultOptions}
zoom={18}
onClick={(e) => setCoord(e.latLng.toJSON())}
id="map"
>
<Marker
position={coord}
onPositionChanged={getData(
coord.lat,
coord.lng
)}
icon={{
url: "https://cdn-icons-png.flaticon.com/512/6147/6147668.png",
origin: new window.google.maps.Point(
0,
0
),
anchor: new window.google.maps.Point(
15,
15
),
scaledSize: new window.google.maps.Size(
30,
30
),
}}
/>
</GoogleMap>
</div>
</div>
<div className="bottomFormBlock">
<div className="otherOfferDataBlock">
<Form.Item name="goodCategoryId">
<Select>
{data?.map((res, idx) => (
<Option value={idx + 1} key={idx}>
{res.name}
</Option>
))}
</Select>
</Form.Item>
<Form.Item name="startDate">
<DatePicker />
</Form.Item>
<Form.Item
name="goodsWeight"
rules={[
{
message:
inputValidationErrors.EMPTY_GOOD_WEIGHT_MESSAGE,
},
{
required: true,
message:
inputValidationErrors.EMPTY_GOOD_WEIGHT_MESSAGE,
},
]}
>
<Input
type="number"
placeholder="Goods Weight"
/>
</Form.Item>
</div>
<div className="otherOfferDataBlock">
<Form.Item
name="description"
className="description"
rules={[
{
message:
inputValidationErrors.EMPTY_DESCRIPTION_MESSAGE,
},
{
required: true,
message:
inputValidationErrors.EMPTY_DESCRIPTION_MESSAGE,
},
]}
>
<TextArea placeholder="Description" />
</Form.Item>
<Form.Item>
<Button
type="primary"
htmlType="submit"
className="submitButton"
>
Create offer
</Button>
</Form.Item>
</div>
</div>
</Form>
</div>
</>
) : (
<>
<span>Map is not loaded!</span>
</>
);
}
If you are getting the address of the clicked location, which it looks like you are doing in getData function, pass the address into setValue().
const getData = (lat, lng) => {
Geocode.fromLatLng(lat, lng).then(
(response) => {
const address = response.results[0].formatted_address;
setValue(address)

How to get dynamically selected value from material ui autocomplete

We can get TextField value dynamically with [evt.target.name]: evt.target.value but
How can I get Autocomplete selected value dynamically, Like bellow example:
import { useState } from 'react'
import Autocomplete from '#mui/material/Autocomplete'
import TextField from '#mui/material/TextField'
import Button from '#mui/material/Button'
const brands = ['niki', 'adidas', 'ramond', 'oliver', 'zara', 'casely']
const categories = ['pant', 'shirt']
const inputItems = [
{ label: 'Product Name', type: 'text', name: 'name' },
{ label: 'Brand', type: 'text', name: 'brand', options: brands },
{ label: 'Category', type: 'text', name: 'category', options: categories },
{ label: 'Price', type: 'number', name: 'price' },
{ label: 'Description', type: 'text', name: 'description' },
{ label: 'Image', type: 'text', name: 'image' },
]
const inputItemsObj = {}
inputItems.forEach(item => inputItemsObj[item.name] = '')
const Products = () => {
const [ fields, setFields ] = useState(inputItemsObj)
const [ fieldsError, setFieldsError ] = useState(inputItemsObj)
const changeHandler = (evt, newValue, action, option ) => {
setFields({ ...fields,[evt.target.name]: evt.target.value })
}
const submitHandler = (evt) => {
evt.preventDefault()
console.log(fields)
}
return (
<form noValidate onSubmit={submitHandler}>
{inputItems.map(({label, type, name, options}, key) => (name === 'category' || name === 'brand') ? (
<Autocomplete key={key}
options={options}
getOptionLabel={option => option}
renderInput={ params => <TextField {...params}
label={label}
placeholder={label}
type={type}
fullWidth
margin='dense'
InputLabelProps={{ shrink: true }}
name={name}
error={!fields[name] || !!fieldsError[name]}
helperText={fieldsError[name]}
/>}
name={name}
value={options[0]}
onChange={changeHandler}
/>
) : (
<TextField key={key}
label={label}
placeholder={label}
type={type}
fullWidth
autoFocus={key === 0}
margin='dense'
InputLabelProps={{ shrink: true }}
name={name}
value={fields[name]}
onChange={changeHandler}
multiline
rows={name === 'description' ? 3 : 1}
error={!fields[name] || !!fieldsError[name]}
helperText={fieldsError[name]}
/>
))}
<Button type='submit' variant='contained' >Submit</Button>
</form>
)
}
export default Products
The second value of onChange will give you a list of all the selected values.
function(event: React.SyntheticEvent, value: T | Array<T>, reason: string, details?: string) => void
So in your example use newValue rather than evt in your changeHandler
More info found here: https://mui.com/api/autocomplete/
Edit: I don't think you will be able to get the name from evt.target.name so some solution like this should work.
const changeHandler = (name) => (evt, newValue, action, option ) => {
// Also as you are updating/adding to state a callback should be used in setFields
setFields((prevState) => ({ ...prevState, [name]: newValue }))
}
Then in the Autocomplete:
<Autocomplete key={key}
//...other props
onChange={changeHandler(name)}
/>

My react-dropdown-select item is undefined

I am attempting to parse the dropdown item that is selected into a Prop. I get an error of
TypeError: Cannot read property 'name' of undefined
I have attempted to make a new Prop and parse it through there and that did not work either. I have also tried to add all array into the formData to no avail.
When I do not add the dropdown menu the Format and Location are parsed no problem, as soon as they change to the dropdown's it does not get read. I think the dropdowns change them into another format and not a string. .
The addFixture.js code is below:
const AddFixture = ({ addFixture, history }) => {
const [formData, setFormData] = useState({
teams: '',
opposition: '',
date: '',
format: '',
location: '',
});
const {
teams,
opposition,
date,
format,
location
} = formData;
const overs = [
{ value: '40 Overs', label: '40 Overs' },
{ value: '20 Overs', label: '20 Overs' },
]
const hOrA = [
{ value: 'Home', label: 'Home' },
{ value: 'Away', label: 'Away' },
]
const onChange = (e) =>
setFormData({ ...formData, [e.target.name]: e.target.value });
<form
className="form"
onSubmit={(e) => {
e.preventDefault();
addFixture(formData, history);
}}
>
<div className="form-group">
<Select
type="text"
placeholder="* Location"
name="location"
value={location}
options={hOrA}
onChange={onChange}
required
/>
</div>
<div className="form-group">
<Select
type="text"
placeholder="* format"
name="format"
value={format}
onChange={onChange}
options={overs}
required
/>
</div>
</form>
);
};
AddFixture.propTypes = {
addFixture: PropTypes.func.isRequired
};
React select expects the value to match one of the dropdown values - So
value={location} //needs to match the object {value:string, label:string}
React select passes in the full value of the selected option to the onChange so
onChange={onChange} //onChange={(val:{value:label}) => {}}
You can pass in the name of the dropdown like so
onChange={(val) => onChange(val,nameOfDropdown )}
Then use the name passed in like so
const onChange = (selected, name) =>{
setFormData({ ...formData, [name]: selected.value });
}
With all these changes your code should look something like this
const AddFixture = () => {
const [formData, setFormData] = useState({
format: '',
location: '',
});
const {
format,
location
} = formData;
const overs = [
{ value: '40 Overs', label: '40 Overs' },
{ value: '20 Overs', label: '20 Overs' },
]
const hOrA = [
{ value: 'Home', label: 'Home' },
{ value: 'Away', label: 'Away' },
]
/** onChange will get passed value from the dropdown {value:string, label:string} */
const onChange = (selected, name) =>{
setFormData({ ...formData, [name]: selected.value });
}
return(
<>
<div className="form-group">
<Select
type="text"
placeholder="* Location"
name="location"
/** Need to set this to one of the dropdown values {value:string, label:string} */
value={hOrA.find((val) => val.value === location)}
options={hOrA}
onChange={(val) => onChange(val,"location" )}
required
/>
</div>
<div className="form-group">
<Select
type="text"
placeholder="* format"
name="format"
/** Need to set this to one of the dropdown values {value:string, label:string} */
value={hOrA.find((val) => val.value === format)}
onChange={(val) => onChange(val,"format" )}
options={overs}
required
/>
</div>
</>
);
};

React.js: How to pass onchange value of listbox to function?

I'm trying to pass value from the onchange of listbox to a function called handleOnChange
In the handleOnChange function, I set the value to state (array)
However, I get an error when I try to add curly braces when enclosing selected
Eventually, I will be trying to pass this as a json request
ProfileMaintenancePage.js
const [selectedModules, setSelectedModules] = useState([]);
const handleOnChange = (selected) => {
console.log("selected " + selected)
setSelectedModules(selected)
};
return (
<DualListBox
options={ newOptionsListbox }
selected={ selectedModules }
onChange={ handleOnChange }
showHeaderLabels={ true }
disabled={ disabled }
/>
)
The value is passed correctly to the handleOnChange
Is this the correct way to set this on the state?
How can I access this from the state?
TIA
EDIT:
Full page code of ProfileMaintenancePage.js
import React, {useState, useCallback, useEffect, useRef} from 'react';
import { MDBCard, MDBCardBody, MDBBreadcrumb, MDBBreadcrumbItem, MDBDataTable, MDBCol, MDBBtn } from 'mdbreact';
import 'react-bootstrap-table-next/dist/react-bootstrap-table2.min.css';
import BootstrapTable from 'react-bootstrap-table-next';
import paginationFactory from 'react-bootstrap-table2-paginator';
import filterFactory, { textFilter } from 'react-bootstrap-table2-filter';
import 'react-dual-listbox/lib/react-dual-listbox.css';
import DualListBox from 'react-dual-listbox';
import ProfileMaintenanceService from '../../services/ProfileMaintenanceService';
const ProfileMaintenancePage = () => {
const [data, setData] = useState([]);
const [listboxModules, setListboxModules] = useState([]); /* populate modules listbox */
const [selectedModules, setSelectedModules] = useState([]); /* store selected modules */
const [modulesIds, setModuleIds] = useState(''); /* store selected modules */
const [listboxActions, setListboxActions] = useState([]); /* populate modules listbox */
const [name, setName] = useState('');
const [disabled, setDisabled] = useState(false);
const retrieveModulesList = useCallback(() => {
ProfileMaintenanceService.retrieveModulesList()
.then((response) => {
console.log("ProfileMaintenancePage - retrieveModulesList response.data >>> " + response.data)
console.log("ProfileMaintenancePage - retrieveModulesList JSON.stringify(response.data) >>> " + JSON.stringify(response.data))
setListboxModules(response.data);
}).catch((err) => {
console.log("ProfileMaintenancePage - retrieveModulesList catch >>> " + err)
})
});
const retrieveActionsList = useCallback((selectedModules) => {
ProfileMaintenanceService.retrieveActionsList(selectedModules)
.then((response) => {
console.log("ProfileMaintenancePage - retrieveActionsList response.data >>> " + response.data)
console.log("ProfileMaintenancePage - retrieveActionsList JSON.stringify(response.data) >>> " + JSON.stringify(response.data))
setListboxActions(response.data);
}).catch((err) => {
console.log("ProfileMaintenancePage - retrieveActionsList catch >>> " + err)
})
});
useEffect(() => {
retrieveModulesList();
}, []);
/* CLIENT */
const columnsClient = [
{
headerStyle: {
backgroundColor: '#a6a6a6'
},
dataField: 'name',
text: 'Name',
sort: true,
filter: textFilter()
},
{
headerStyle: {
backgroundColor: '#a6a6a6'
},
dataField: 'creator',
text: 'Creator',
sort: true
// filter: textFilter()
},
{
headerStyle: {
backgroundColor: '#a6a6a6'
},
dataField: 'creationdate',
text: 'Creation Date',
sort: true
// filter: textFilter()
},
{
headerStyle: {
backgroundColor: '#a6a6a6'
},
dataField: 'lastmodifier',
text: 'Last Modifier',
sort: true
// filter: textFilter()
},
{
headerStyle: {
backgroundColor: '#a6a6a6'
},
dataField: 'lastmodification',
text: 'Last Modification',
sort: true
// filter: textFilter()
},
];
const selectRowClient = {
mode: 'checkbox',
clickToSelect: true,
clickToEdit: false,
hideSelectAll: false,
hideSelectColumn: false,
onSelect: (row, isSelect, rowIndex) => {
}
};
/* Pagination */
const customTotal = (from, to, size) => (
<span className="react-bootstrap-table-pagination-total">
Showing { from } to { to } of { size } Results
</span>
);
const options = {
paginationSize: 4,
pageStartIndex: 0,
alwaysShowAllBtns: true,
hideSizePerPage: true,
firstPageText: 'First',
prePageText: 'Back',
nextPageText: 'Next',
lastPageText: 'Last',
nextPageTitle: 'First page',
prePageTitle: 'Pre page',
firstPageTitle: 'Next page',
lastPageTitle: 'Last page',
showTotal: true,
paginationTotalRenderer: customTotal,
sizePerPageList: [{
text: '5', value: 5
}, {
text: '10', value: 10
}, {
text: 'All', value: data.length
}]
};
/* CLIENT -- end */
const newOptionsListbox = listboxModules.map(({id, module, description}) => ({
id: id,
label: module,
value: id /* temporarily set to id but it should be description */
}))
const newOptionsListbox2 = listboxModules.map(({id, module, description}) => ({
id: "",
label: "",
value: "" /* temporarily set to id but it should be description */
}))
const handleOnChange = (selected) => {
console.log("selected " + selected)
setSelectedModules( selected )
// setModuleIds(selectedValues)
retrieveActionsList()
};
const addProfile = () => {
setDisabled(false);
};
return (
<div>
<MDBCard className="mb-2">
<MDBCardBody id="breadcrumb" className="d-flex align-items-center justify-content-between">
<MDBBreadcrumb>
<MDBBreadcrumbItem>Administrator</MDBBreadcrumbItem>
<MDBBreadcrumbItem active>Profile Maintenance</MDBBreadcrumbItem>
</MDBBreadcrumb>
</MDBCardBody>
</MDBCard>
<MDBCard className="mb-2">
<MDBCardBody>
<MDBCard className="mb-2">
<MDBCardBody>
<MDBCard className="mb-2">
<MDBCardBody>
<MDBCol md="12">
<form className="form-horizontal form-group">
<div className="text-left mt-2">
<MDBBtn color="indigo" type="button" onClick={() => { addProfile(); }}>Add</MDBBtn>
<MDBBtn color="indigo" type="button" onClick={() => {}}>Delete</MDBBtn>
</div>
</form>
</MDBCol>
<BootstrapTable
keyField='id'
hover
data={ '' }
columns={ columnsClient }
filter={ filterFactory() }
selectRow={ selectRowClient }
noDataIndication="No record(s) found."
pagination={ paginationFactory(options) }
/>
</MDBCardBody>
</MDBCard>
<MDBCol md="6">
<br />
<label htmlFor="name" className="dark-grey-text">
Name
</label>
<input type="text" id="name" className="form-control"
value={name} onChange={e => setName(e.target.value)} disabled={disabled} />
</MDBCol>
<MDBCol md="12">
<br />
<label htmlFor="entities" className="dark-grey-text">
Modules
</label>
<DualListBox
options={ newOptionsListbox }
selected={ selectedModules }
onChange={ handleOnChange }
showHeaderLabels={ true }
disabled={ disabled }
/>
<br />
<label htmlFor="entities" className="dark-grey-text">
Actions
</label>
{/* <DualListBox
options={ newOptionsListbox2 }
selected={ selectedModules }
onChange={ onChange }
showHeaderLabels={ true }
disabled={ disabled }
/> */}
<br />
</MDBCol>
<MDBCol md="12">
<form className="form-horizontal form-group">
<div className="text-right mt-2">
<MDBBtn color="indigo" type="button" onClick={() => {}}>Export</MDBBtn>
<MDBBtn color="indigo" type="button" onClick={() => {}}>Cancel</MDBBtn>
<MDBBtn color="indigo" type="button" onClick={() => {}}>Save</MDBBtn>
</div>
</form>
</MDBCol>
</MDBCardBody>
</MDBCard>
</MDBCardBody>
</MDBCard>
</div>
);
}
export default ProfileMaintenancePage;
Issue:
When using this function, I can't seem to access the value of the state specifically selectedModules
const retrieveActionsList = useCallback((selectedModules) => {
ProfileMaintenanceService.retrieveActionsList(selectedModules)
.then((response) => {
console.log("ProfileMaintenancePage - retrieveActionsList response.data >>> " + response.data)
console.log("ProfileMaintenancePage - retrieveActionsList JSON.stringify(response.data) >>> " + JSON.stringify(response.data))
setListboxActions(response.data);
}).catch((err) => {
console.log("ProfileMaintenancePage - retrieveActionsList catch >>> " + err)
})
});
I think what you want is an array in the state, but you always overwrite your array with one element.
So selectedModuels woud be <DualListBox /> always.
If you want to push it, you could use:
newState = selectedModules.slice();
newState.push(selected);
setSelectedModules(newState);

Dialog popup not displaying rowData react

I am new to react and working on a table with MaterialUI. It is an editable table and I am trying to have an icon that returns a dialog box. I can get the dialog returned but when trying to pass through the rowData I get nothing. I have tried useState (probably using it wrong) and also trying to pass the data as a parameter.
See code below
export default function MaterialTableDemo() {
const [state, setState] = React.useState({
columns : [
{ title: "Program", field: "Program", defaultFilter: "Program" },
{
title: 'Program Type',
field: 'ProgramType',
lookup: { 1: 'Assignment', 2: 'Auto', 3: 'Default' },
},
],
data : [
{ Program: 'Program', ProgramType: 1 },
{ Program: 'Program 2', ProgramType: 3 },
],
});
function handleOnClose() {
setOpen(false)
}
function handleOnOpen() {
setOpen(true)
//console.log(rowData);
}
const [open, setOpen] = React.useState(false);
const [close, setClose] = React.useState();
return (
<div className="section">
<h6>filtering</h6>
<MaterialTable
columns={state.columns}
icons={tableIcons}
data={state.data}
dataIcon = {rowData => {
return (
console.log(rowData),
React.useState(rowData)
)
}}
detailPanel={rowData => {
return (
console.log(rowData),
<div>
<h2>Expired Time </h2> <br></br>
<span>{rowData.ExpireDate}</span>
<br></br>
<Popup modal trigger={<button>Edit </button>}>
{close => <Content close={close} />}
</Popup>
</div>
)
}}
options={{
filtering: true
}}
actions={rowData => {
return (
console.log(rowData)
)},
[
{
icon: tableIcons.Star,
tooltip: 'Popup to Edit',
onClick: (event, handleOnOpen)
},
]}
title="Program"
editable={{
onRowAdd: newData =>
new Promise(resolve => {
setTimeout(() => {
resolve();
setState(prevState => {
const data = [...prevState.data];
data.push(newData);
return { ...prevState, data };
});
}, 600);
}),
onRowUpdate: (newData, oldData) =>
new Promise(resolve => {
setTimeout(() => {
resolve();
if (oldData) {
setState(prevState => {
const data = [...prevState.data];
data[data.indexOf(oldData)] = newData;
return { ...prevState, data };
});
}
}, 600);
}),
onRowDelete: oldData =>
new Promise(resolve => {
setTimeout(() => {
resolve();
setState(prevState => {
const data = [...prevState.data];
data.splice(data.indexOf(oldData), 1);
return { ...prevState, data };
});
}, 600);
}),
}
}
/>
<Dialog
open={open}
onClose={handleOnClose}
aria-labelledby="draggable-dialog-title"
>
<DialogTitle id="draggable-dialog-title">Edit Program</DialogTitle>
<DialogContent>
<DialogContentText>
Edit Program
</DialogContentText>
<div className="group">
{" "}
<label label for="ProgramCode"><b> Program: </b></label>
<input align="right" type="ProgramCode" placeholder="Enter Program Code" align="right" width="300" required></input>
</div>
<div className="group">
{" "}
<label for="ProgramTypeCode"><b> Program Type: </b></label>
<input type="ProgramTypeCode" placeholder="Enter Program Type" align="right" width="300" name="CPTC" required></input>
</div>
<br></br>
<button>Save</button>
</DialogContent>
</Dialog>
<br></br>
</div>
);
}

Resources