How to change value in GooglePlacesAutocomplete - reactjs

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)

Related

Why am i POST a lot of unwanted data?

I'm kind of new with java and ReactJS and I have a big issue where when I tried to post my data, it posted a lot of unwanted data like rendering the whole table.
My console.log() printed this :
location_dest_id: 2
location_id: 1
origin: "test3"
picking_type_id: 1
stock_move_ids: Array(1)
0:
altKey: false
bubbles: true
button: 0
buttons: 0
cancelable: true
clientX: 317
clientY: 652
ctrlKey: false
currentTarget: null
defaultPrevented: false
demand: "12"
detail: 1
done: "0"
eventPhase: 3
getModifierState: ƒ modifierStateGetter(keyArg)
isDefaultPrevented: ƒ functionThatReturnsFalse()
isPropagationStopped: ƒ functionThatReturnsFalse()
isTrusted: true
metaKey: false
movementX: 0
movementY: 0
nativeEvent: PointerEvent {isTrusted: true, pointerId: 1, width: 1,
height: 1, pressure: 0, …}
pageX: 317
pageY: 754
product_tmpl_id: 9
product_uom: "1"
relatedTarget: null
screenX: 317
screenY: 723
shiftKey: false
target: span
timeStamp: 203547.59999990463
type: "click"
view: Window {window: Window, self: Window, document: document, name: '', location: Location, …}
_reactName: "onClick"
_targetInst: null
From what I understand, the error is when I tried to pass "stock_move_ids" nested data, it POST so much data as like the console.log() above. What it should be passed is like this :
[
{
"date":"02-09-2022",
"origin":"test2",
"picking_type_id":2,
"location_id":1,
"location_dest_id":2,
"stock_move_ids":
[
{
"demand":12,
"done":0,
"product_uom":1,
"product_tmpl_id":18
}
]
}
]
Is there any way to solve my problem? My code is based on this template : https://codesandbox.io/s/j0opp
Here's my code looks like :
Parent
import React, { useEffect, useContext } from "react";
import { Button, Form, Input, DatePicker, Select } from 'antd';
import { Stockmovetable } from "./Stockmovetable";
import { AppContext } from '../../../context/Appcontext'
const Stockpickingnew = ({ title }) => {
const { Function, State } = useContext(AppContext)
const { fetchDataPickingType, fetchDataLocation, fetchDataPupuk, option, stock_move_ids, StockPick, StockPickFailed } = Function
const { dateFormat, dataPupuk, dataStockLocation, dataStockPickingType } = State
useEffect(() => {
fetchDataPickingType()
fetchDataLocation()
fetchDataPupuk()
}, [])
return (
<>
<div className='new'>
<div className="top">
<h1>{title}</h1>
</div>
<div className="bottom">
<div className="stockPicking">
<Form
name="stockPickings"
layout="vertical"
onFinish={StockPick}
onFinishFailed={StockPickFailed}
autoComplete="off"
>
<div className="left">
<Form.Item
label="Origin :"
name='origin'
>
<Input placeholder="Origin" />
</Form.Item>
<Form.Item
label="Picking Type :"
name='picking_type_id'
>
<Select
placeholder="Picking Type"
options={dataStockPickingType.map(e => ({label: e.name, value: e.id}))}
/>
</Form.Item>
<Form.Item
label="Date :"
name='date'
>
<DatePicker
format={dateFormat}
/>
</Form.Item>
</div>
<div className="right">
<Form.Item
label="Location :"
name='location_id'
>
<Select
placeholder="Tujuan Awal"
options={dataStockLocation.map(e => ({label: e.name, value: e.id}))}
/>
</Form.Item>
<Form.Item
label="Destination :"
name='location_dest_id'
>
<Select
placeholder="Tujuan Akhir"
options={dataStockLocation.map(e => ({label: e.name, value: e.id}))}
/>
</Form.Item>
</div>
<div className="stockMove">
<Form.List name="stock_move_ids">
{(stock_move_ids, { add, remove }) => {
return <Stockmovetable stock_move_ids={stock_move_ids} option={option} add={add} remove={remove} dataPupuk={dataPupuk} />;
}}
</Form.List>
</div>
<Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
</div>
</div>
</div>
</>
)
}
export default Stockpickingnew
Child
import React from "react";
import { Form, Input, Button, Table, Select } from "antd";
import { PlusOutlined, MinusOutlined } from "#ant-design/icons";
const { Column } = Table;
export const Stockmovetable = props => {
const { stock_move_ids, add, remove, dataPupuk, option } = props;
return (
<Table
dataSource={stock_move_ids}
pagination={false}
footer={() => {
return (
<Form.Item>
<Button onClick={add}>
<PlusOutlined /> Add field
</Button>
</Form.Item>
);
}}
>
<Column
dataIndex={"product_tmpl_id"}
title={"Nama Produk"}
render={(value, row, index) => {
return (
<Form.Item name={[index, "product_tmpl_id"]}>
<Select
placeholder="Produk"
options={dataPupuk.map(e => ({ label: e.name, value: e.id }))}
/>
</Form.Item>
);
}}
/>
<Column
dataIndex={"demand"}
title={"Demand"}
render={(value, row, index) => {
// console.log(row);
return (
<Form.Item name={[index, "demand"]}>
<Input
placeholder="Demand"
/>
</Form.Item>
);
}}
/>
<Column
dataIndex={"done"}
title={"Done"}
render={(value, row, index) => {
return (
<Form.Item name={[index, "done"]}>
<Select
placeholder="Tujuan Akhir"
options={option}
/>
</Form.Item>
);
}}
/>
<Column
dataIndex={"product_uom"}
title={"product_uom"}
render={(value, row, index) => {
return (
<Form.Item name={[index, "product_uom"]}>
<Input
placeholder="product_uom"
/>
</Form.Item>
);
}}
/>
<Column
title={"Action"}
render={(value, row, index) => {
return (
<React.Fragment>
<Button
icon={<MinusOutlined />}
shape={"circle"}
onClick={() => remove(row.name)}
/>
</React.Fragment>
);
}}
/>
</Table>
);
};
Context
export const AppContext = createContext()
export const AppProvider = props => {
const Navigate = useNavigate()
const dateFormat = ['DD-MM-YYYY'];
const StockPick = (values) => {
console.log('Success:', values);
let stockpick = [{
date: moment(values.date).format("DD-MM-YYYY"),
origin: values.origin,
picking_type_id: values.picking_type_id,
location_id: parseInt(values.location_id),
location_dest_id: parseInt(values.location_dest_id),
stock_move_ids: [
{
demand: parseInt(values?.stock_move_ids?.[0]?.demand),
done: parseInt(values?.stock_move_ids?.[0]?.done),
product_uom: parseInt(values?.stock_move_ids?.[0]?.product_uom),
product_tmpl_id: values?.stock_move_ids?.[0]?.product_tmpl_id,
},
],
}];
let params = JSON.stringify(stockpick)
console.log(params)
axios.post('http://127.0.0.1:5000/api/stockpickings', params, { headers })
.then(() => {
Navigate('/')
})
.catch(error => {
if (error.response) {
console.log(error.response);
}
});
};
}
I think this is all I can provide / needed to fix my codings, if there's anything I need to add and or fix, please tell me. Thank you.
Okay after some hours tries
as the comment above, i think all i need to do is just not making the body as dataindex.
from :
<Form.List name="stock_move_ids">
{(stock_move_ids, { add, remove }) => {
return <Stockmovetable stock_move_ids={stock_move_ids} option={option} add={add} remove={remove} dataPupuk={dataPupuk} />;
}}
</Form.List>
to
<Form.List name="stock_move_ids">
{(stock_move, { add, remove }) => {
return <Stockmovetable stock_move_ids={stock_move_ids} option={option} add={add} remove={remove} dataPupuk={dataPupuk} />;
}}
</Form.List>
Thank you very much for the helps!

Error: Objects are not valid as a React child (found: Error: Network Error). If you meant to render a collection of children, use an array instead

I am facing this issue while submitting a form. I want to take inputs from the form and show it into the list.
I am getting an error which is
Error: Objects are not valid as a React child (found: Error: Network Error). If you meant to render a collection of children, use an array instead.
this is the add user form
import { Row, Col, Form, Input, Select, DatePicker, Radio, InputNumber, Upload, Spin } from 'antd';
import { Link } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import FeatherIcon from 'feather-icons-react';
import { RecordFormWrapper } from './Style';
import { PageHeader } from '../../../components/page-headers/page-headers';
import { Cards } from '../../../components/cards/frame/cards-frame';
import { Button } from '../../../components/buttons/buttons';
import { Main, BasicFormWrapper } from '../../styled';
import { usernewDataSubmit } from '../../../redux/crud/usernew/actionCreator';
// import Heading from '../../../components/heading/heading';
const { Option } = Select;
const dateFormat = 'YYYY/MM/DD';
const AddNew = () => {
const dispatch = useDispatch();
const { isLoading, } = useSelector(state => {
return {
isLoading: state.UserNewCrud.loading,
};
});
const [form] = Form.useForm();
const [state, setState] = useState({
join: '',
dob: '',
});
const handleSubmit = values => {
dispatch(
usernewDataSubmit({
...values,
join: state.join,
dob: state.dob,
id: new Date().getTime(),
}),
);
form.resetFields();
dispatch(usernewFileClear());
};
const onChange = (date, dateString) => {
setState({ join: dateString });
};
// const props = {
// name: 'file',
// action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
// multiple: false,
// showUploadList: false,
// headers: {
// authorization: 'authorization-text',
// },
// onChange(info) {
// if (info.file.status !== 'uploading') {
// dispatch(usernewFileUploder(info.file.originFileObj));
// }
// if (info.file.status === 'done') {
// // message.success(`${info.file.name} file uploaded successfully`);
// } else if (info.file.status === 'error') {
// // message.error(`${info.file.name} file upload failed.`);
// }
// },
// };
return (
<>
<PageHeader
// buttons={[
// <Button className="btn-add_new" size="default" key="1" type="primary">
// <Link to="/admin/crud/usernew-view">View All</Link>
// </Button>,
// ]}
ghost
title="Add New User"
/>
<Main>
<Row gutter={15}>
<Col xs={24}>
<Form name="sDash_validation-form" form={form} layout="vertical" onFinish={handleSubmit}>
<Row gutter={30}>
<Col md={12} xs={24}>
<Form.Item name="name" label="Full Name">
<Input placeholder="Enter you full Name" />
</Form.Item>
</Col>
<Col md={12} xs={24}>
<Form.Item name="email" rules={[{ type: 'email' }]} label="Email Address">
<Input placeholder="name#example.com" />
</Form.Item>
</Col>
<Col md={12} xs={24}>
<Form.Item name="phone" label="Phone Number">
<InputNumber type="number" placeholder="+44 2546 5236" style={{ width: '100%' }} />
</Form.Item>
</Col>
<Col md={12} xs={24}>
<Form.Item name="address" label="Full Address">
<Input placeholder="Enter your complete address" />
</Form.Item>
</Col>
<Col md={12} xs={24}>
<Form.Item name="postal_code" label="Postal/Zip/Pin Code">
<InputNumber type="number" placeholder="160071" style={{ width: '100%' }} />
</Form.Item>
</Col>
<Col md={12} xs={24}>
<Form.Item name="country" initialValue="" label="Country">
<Select style={{ width: '100%' }}>
<Option value="">Please Select</Option>
<Option value="russia">Russia</Option>
<Option value="india">India</Option>
<Option value="uk">United Kingdom</Option>
<Option value="usa">United States</Option>
</Select>
</Form.Item>
</Col>
<Col md={8} xs={24}>
<Form.Item name="state" label="State">
<Input placeholder="Enter state Name" />
</Form.Item>
</Col>
<Col md={8} xs={24}>
<Form.Item name="city" label="City">
<Input placeholder="Enter city name" />
</Form.Item>
</Col>
<Col md={8} xs={24}>
<Form.Item rules={[{ type: 'object', whitespace: true }]} label="Date of Birth">
<DatePicker onChange={onChange} format={dateFormat} style={{ width: '100%', padding: '12px' }} />
</Form.Item>
</Col>
<Col md={8} xs={24}>
<Form.Item rules={[{ type: 'object', whitespace: true }]} label="Joining Date">
<DatePicker onChange={onChange} format={dateFormat} style={{ width: '100%', padding: '12px' }} />
</Form.Item>
</Col>
<Col md={8} xs={24}>
<Form.Item name="gender" initialValue="" label="Gender">
<Radio.Group>
<Radio value="male">Male</Radio>
<Radio value="female">Female</Radio>
<Radio value="others">Others</Radio>
</Radio.Group>
</Form.Item>
</Col>
<Col md={8} xs={24}>
<Form.Item name="status" initialValue="" label="Status">
<Radio.Group>
<Radio value="active">Active</Radio>
<Radio value="inactive">Inactive</Radio>
</Radio.Group>
</Form.Item>
</Col>
{/* <Col md={8} xs={24}>
<Form.Item name="address_type" initialValue="active" label="Address type">
<Radio.Group>
<Radio value="home">Home</Radio>
<Radio value="work">Work</Radio>
<Radio value="other">Other</Radio>
</Radio.Group>
</Form.Item>
</Col> */}
</Row>
<Form.Item>
<div className="add-user-bottom text-right">
<Button
className="ant-btn ant-btn-primary"
type="danger"
onClick={() => {
return form.resetFields();
}}
>
Reset
</Button>
<Button htmlType="Save" type="primary">
{isLoading ? 'Loading...' : 'Submit'}
</Button>
</div>
</Form.Item>
{/* <div className="sDash_form-action mt-20">
<Button htmlType="submit" type="primary" size="large">
Submit Form
</Button>
</div>*/}
</Form>
{/* <RecordFormWrapper>
<Cards headless>
<Row justify="center">
<Col xl={10} md={16} xs={24}>
<BasicFormWrapper>
<Form
className="add-record-form"
style={{ width: '100%' }}
layout="vertical"
form={form}
name="addnew"
onFinish={handleSubmit}
>
<figure className="pro-image align-center-v">
<img
src={
url === null
? require('../../../static/img/avatar/profileImage.png')
: `https://demo.jsnorm.com/laravel/strikingdash/${url}`
}
alt=""
/>
<figcaption>
<Upload {...props}>
<Link className="upload-btn" to="#">
<FeatherIcon icon="camera" size={16} />
</Link>
</Upload>
<div className="info">
<Heading as="h4">Profile Photo</Heading>
</div>
{isFileLoading && (
<div className="isUploadSpain">
<Spin />
</div>
)}
</figcaption>
</figure>
<Form.Item name="name" label="Name">
<Input placeholder="Input Name" />
</Form.Item>
<Form.Item name="email" rules={[{ type: 'email' }]} label="Email">
<Input placeholder="example#gmail.com" />
</Form.Item>
<Form.Item name="country" initialValue="" label="Country">
<Select style={{ width: '100%' }}>
<Option value="">Please Select</Option>
<Option value="bangladesh">Bangladesh</Option>
<Option value="india">India</Option>
<Option value="pakistan">Pakistan</Option>
<Option value="srilanka">Srilanka</Option>
</Select>
</Form.Item>
<Form.Item name="city" initialValue="" label="City">
<Select style={{ width: '100%' }}>
<Option value="">Please Select</Option>
<Option value="dhaka">Dhaka</Option>
<Option value="mymensingh">Mymensingh</Option>
<Option value="khulna">Khulna</Option>
<Option value="barisal">Barisal</Option>
</Select>
</Form.Item>
<Form.Item name="company" label="Company">
<Input placeholder="Company Name" />
</Form.Item>
<Form.Item name="position" label="Position">
<Input placeholder="Position" />
</Form.Item>
<Form.Item label="Joining Date">
<DatePicker onChange={onChange} style={{ width: '100%' }} format={dateFormat} />
</Form.Item>
<Form.Item name="status" label="Status">
<Radio.Group>
<Radio value="active">Active</Radio>
<Radio value="deactivated">Deactivated</Radio>
<Radio value="blocked">Blocked</Radio>
</Radio.Group>
</Form.Item>
<div className="record-form-actions text-right">
<Button size="default" htmlType="Save" type="primary">
{isLoading ? 'Loading...' : 'Submit'}
</Button>
</div>
</Form>
</BasicFormWrapper>
</Col>
</Row>
</Cards>
</RecordFormWrapper> */}
</Col>
</Row>
</Main>
</>
);
};
export default AddNew;
//This is actionCreator file
import { notification } from 'antd';
import actions from './actions';
import { DataService } from '../../../config/dataService/dataService';
const addNotificationSuccess = () => {
notification.success({
message: 'Your Record has been Submited',
});
};
const addNotificationError = err => {
notification.error({
message: err,
});
};
const deleteNotificationSuccess = () => {
notification.success({
message: 'Your Record has been Deleted',
});
};
const deleteNotificationError = err => {
notification.error({
message: err,
});
};
const updateNotificationSuccess = () => {
notification.success({
message: 'Your Record has been updated',
});
};
const updateNotificationError = err => {
notification.error({
message: err,
});
};
const {
usernewAddBegin,
usernewAddSuccess,
usernewAddErr,
usernewReadBegin,
usernewReadSuccess,
usernewReadErr,
usernewUpdateBegin,
usernewUpdateSuccess,
usernewUpdateErr,
usernewDeleteBegin,
usernewDeleteSuccess,
usernewDeleteErr,
usernewSingleDataBegin,
usernewSingleDataSuccess,
usernewSingleDataErr,
} = actions;
const usernewDataSubmit = data => {
return async dispatch => {
try {
await dispatch(usernewAddBegin());
const response = await DataService.post('/create', data);
await dispatch(usernewAddSuccess(response.data.data));
await addNotificationSuccess();
} catch (err) {
await dispatch(usernewAddErr(err));
await addNotificationError(err);
}
};
};
const usernewDataRead = () => {
return async dispatch => {
try {
await dispatch(usernewReadBegin());
const query = await DataService.get('/view-all');
await dispatch(usernewReadSuccess(query.data.data));
} catch (err) {
await dispatch(usernewReadErr(err));
}
};
};
const usernewCrudGetData = () => {
return async dispatch => {
try {
await dispatch(usernewReadBegin());
const query = await DataService.get('/view-all');
await dispatch(usernewReadSuccess(query.data.data));
} catch (err) {
await dispatch(usernewReadErr(err));
}
};
};
const usernewDataSearch = searchItem => {
return async dispatch => {
try {
await dispatch(usernewReadBegin());
if (searchItem !== '') {
const query = await DataService.get(`/search/${searchItem}`);
await dispatch(usernewReadSuccess(query.data.data));
} else {
try {
const query = await DataService.get('/view-all');
await dispatch(usernewReadSuccess(query.data.data));
} catch (err) {
await dispatch(usernewReadErr(err));
}
}
} catch (err) {
await dispatch(usernewReadErr(err));
}
};
};
const usernewDataUpdate = (id, data) => {
return async dispatch => {
try {
await dispatch(usernewUpdateBegin());
await DataService.post(`/update/${id}`, data);
await dispatch(usernewUpdateSuccess());
updateNotificationSuccess();
} catch (err) {
await dispatch(usernewUpdateErr(err));
updateNotificationError(err);
}
};
};
const usernewDataDelete = ({ id, getData }) => {
return async dispatch => {
try {
await dispatch(usernewDeleteBegin());
const data = await DataService.get(`/delete/${id}`);
await dispatch(usernewDeleteSuccess(data));
await getData();
deleteNotificationSuccess();
} catch (err) {
await dispatch(usernewDeleteErr(err));
deleteNotificationError(err);
}
};
};
const usernewDataSingle = id => {
return async dispatch => {
try {
await dispatch(usernewSingleDataBegin());
const query = await DataService.get(`/view/${id}`);
await dispatch(usernewSingleDataSuccess(query.data.data));
} catch (err) {
await dispatch(usernewSingleDataErr(err));
}
};
};
export {
usernewDataRead,
usernewDataSearch,
usernewDataSubmit,
usernewDataDelete,
usernewCrudGetData,
usernewDataSingle,
usernewDataUpdate,
};
//Below is actions file.
const actions = {
USERNEW_ADD_BEGIN: 'USERNEW_ADD_BEGIN',
USERNEW_ADD_SUCCESS: 'USERNEW_ADD_SUCCESS',
USERNEW_ADD_ERR: 'USERNEW_ADD_ERR',
USERNEW_READ_BEGIN: 'USERNEW_READ_BEGIN',
USERNEW_READ_SUCCESS: 'USERNEW_READ_SUCCESS',
USERNEW_READ_ERR: 'USERNEW_READ_ERR',
USERNEW_UPDATE_BEGIN: 'USERNEW_UPDATE_BEGIN',
USERNEW_UPDATE_SUCCESS: 'USERNEW_UPDATE_SUCCESS',
USERNEW_UPDATE_ERR: 'USERNEW_UPDATE_ERR',
USERNEW_DELETE_BEGIN: 'USERNEW_DELETE_BEGIN',
USERNEW_DELETE_SUCCESS: 'USERNEW_DELETE_SUCCESS',
USERNEW_DELETE_ERR: 'USERNEW_DELETE_ERR',
USERNEW_SINGLE_DATA_BEGIN: 'USERNEW_SINGLE_DATA_BEGIN',
USERNEW_SINGLE_DATA_SUCCESS: 'USERNEW_SINGLE_DATA_SUCCESS',
USERNEW_SINGLE_DATA_ERR: 'USERNEW_SINGLE_DATA_ERR',
usernewAddBegin: () => {
return {
type: actions.USERNEW_ADD_BEGIN,
};
},
usernewAddSuccess: data => {
return {
type: actions.USERNEW_ADD_SUCCESS,
data,
};
},
usernewAddErr: err => {
return {
type: actions.USERNEW_ADD_ERR,
err,
};
},
usernewReadBegin: () => {
return {
type: actions.USERNEW_READ_BEGIN,
};
},
usernewReadSuccess: data => {
return {
type: actions.USERNEW_READ_SUCCESS,
data,
};
},
usernewReadErr: err => {
return {
type: actions.USERNEW_READ_ERR,
err,
};
},
usernewUpdateBegin: () => {
return {
type: actions.USERNEW_UPDATE_BEGIN,
};
},
usernewUpdateSuccess: data => {
return {
type: actions.USERNEW_UPDATE_SUCCESS,
data,
};
},
usernewUpdateErr: err => {
return {
type: actions.USERNEW_UPDATE_ERR,
err,
};
},
usernewDeleteBegin: () => {
return {
type: actions.USERNEW_DELETE_BEGIN,
};
},
usernewDeleteSuccess: data => {
return {
type: actions.USERNEW_DELETE_SUCCESS,
data,
};
},
usernewDeleteErr: err => {
return {
type: actions.USERNEW_DELETE_ERR,
err,
};
},
usernewSingleDataBegin: () => {
return {
type: actions.USERNEW_SINGLE_DATA_BEGIN,
};
},
usernewSingleDataSuccess: data => {
return {
type: actions.USERNEW_SINGLE_DATA_SUCCESS,
data,
};
},
usernewSingleDataErr: err => {
return {
type: actions.USERNEW_SINGLE_DATA_ERR,
err,
};
},
};
export default actions;
//Below is reducers file
import actions from './actions';
const {
USERNEW_ADD_BEGIN,
USERNEW_ADD_SUCCESS,
USERNEW_ADD_ERR,
USERNEW_READ_BEGIN,
USERNEW_READ_SUCCESS,
USERNEW_READ_ERR,
USERNEW_UPDATE_BEGIN,
USERNEW_UPDATE_SUCCESS,
USERNEW_UPDATE_ERR,
USERNEW_DELETE_BEGIN,
USERNEW_DELETE_SUCCESS,
USERNEW_DELETE_ERR,
USERNEW_SINGLE_DATA_BEGIN,
USERNEW_SINGLE_DATA_SUCCESS,
USERNEW_SINGLE_DATA_ERR,
} = actions;
const initialState = {
data: [],
loading: false,
error: null,
};
const initialStateSingle = {
data: null,
loading: false,
error: null,
};
const usernewCrudReducer = (state = initialState, action) => {
const { type, data, err } = action;
switch (type) {
case USERNEW_ADD_BEGIN:
return {
...state,
loading: true,
};
case USERNEW_ADD_SUCCESS:
return {
...state,
data,
error: false,
loading: true,
};
case USERNEW_ADD_ERR:
return {
...state,
error: err,
loading: false,
};
case USERNEW_READ_BEGIN:
return {
...state,
loading: true,
};
case USERNEW_READ_SUCCESS:
return {
...state,
data,
error: false,
loading: false,
};
case USERNEW_READ_ERR:
return {
...state,
error: err,
loading: false,
};
case USERNEW_DELETE_BEGIN:
return {
...state,
loading: true,
};
case USERNEW_DELETE_SUCCESS:
return {
...state,
error: false,
data,
loading: false,
};
case USERNEW_DELETE_ERR:
return {
...state,
error: err,
loading: false,
};
case USERNEW_UPDATE_BEGIN:
return {
...state,
loading: true,
};
case USERNEW_UPDATE_SUCCESS:
return {
...state,
error: false,
loading: false,
};
case USERNEW_UPDATE_ERR:
return {
...state,
error: err,
loading: false,
};
default:
return state;
}
};
const usernewSingleCrudReducer = (state = initialStateSingle, action) => {
const { type, data, err } = action;
switch (type) {
case USERNEW_SINGLE_DATA_BEGIN:
return {
...initialStateSingle,
loading: true,
};
case USERNEW_SINGLE_DATA_SUCCESS:
return {
...initialStateSingle,
data,
error: false,
loading: false,
};
case USERNEW_SINGLE_DATA_ERR:
return {
...initialStateSingle,
error: err,
loading: false,
};
default:
return state;
}
};
export { usernewCrudReducer, usernewSingleCrudReducer };
// Below is dataService file
import axios from 'axios';
import { getItem } from '../../utility/localStorageControl';
const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT;
const authHeader = () => ({
Authorization: `Bearer ${getItem('access_token')}`,
});
const client = axios.create({
baseURL: API_ENDPOINT,
headers: {
Authorization: `Bearer ${getItem('access_token')}`,
'Content-Type': 'application/json',
},
});
class DataService {
static get(path = '') {
return client({
method: 'GET',
url: path,
headers: { ...authHeader() },
});
}
static post(path = '', data = {}, optionalHeader = {}) {
return client({
method: 'POST',
url: path,
data,
headers: { ...authHeader(), ...optionalHeader },
});
}
static patch(path = '', data = {}) {
return client({
method: 'PATCH',
url: path,
data: JSON.stringify(data),
headers: { ...authHeader() },
});
}
static delete(path = '', data = {}) {
return client({
method: 'DELETE',
url: path,
data: JSON.stringify(data),
headers: { ...authHeader() },
});
}
static put(path = '', data = {}) {
return client({
method: 'PUT',
url: path,
data: JSON.stringify(data),
headers: { ...authHeader() },
});
}
}
/**
* axios interceptors runs before and after a request, letting the developer modify req,req more
* For more details on axios interceptor see https://github.com/axios/axios#interceptors
*/
client.interceptors.request.use(config => {
// do something before executing the request
// For example tag along the bearer access token to request header or set a cookie
const requestConfig = config;
const { headers } = config;
requestConfig.headers = { ...headers, Authorization: `Bearer ${getItem('access_token')}` };
return requestConfig;
});
client.interceptors.response.use(
response => response,
error => {
/**
* Do something in case the response returns an error code [3**, 4**, 5**] etc
* For example, on token expiration retrieve a new access token, retry a failed request etc
*/
const { response } = error;
const originalRequest = error.config;
if (response) {
if (response.status === 500) {
// do something here
} else {
return originalRequest;
}
}
return Promise.reject(error);
},
);
export { DataService };```

React ant design reset only one input filed

Im using my project for React ant design 4 . I have some conflict on the form . I want to know how to reset only one (Note) field any one know the solution
Thanks
stazkblitz here
code here
import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Form, Input, Button, Select } from 'antd';
const { Option } = Select;
const layout = {
labelCol: {
span: 8,
},
wrapperCol: {
span: 16,
},
};
const tailLayout = {
wrapperCol: {
offset: 8,
span: 16,
},
};
const Demo = () => {
const [form] = Form.useForm();
const onGenderChange = (value) => {
switch (value) {
case 'male':
form.setFieldsValue({
note: 'Hi, man!',
});
return;
case 'female':
form.setFieldsValue({
note: 'Hi, lady!',
});
return;
case 'other':
form.setFieldsValue({
note: 'Hi there!',
});
return;
}
};
const onFinish = (values) => {
console.log(values);
};
const onReset = () => {
form.resetFields();
};
const onFill = () => {
form.setFieldsValue({
note: 'Hello world!',
gender: 'male',
});
};
return (
<Form {...layout} form={form} name="control-hooks" onFinish={onFinish}>
<Form.Item
name="note"
label="Note"
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item
name="gender"
label="Gender"
rules={[
{
required: true,
},
]}
>
<Select
placeholder="Select a option and change input text above"
onChange={onGenderChange}
allowClear
>
<Option value="male">male</Option>
<Option value="female">female</Option>
<Option value="other">other</Option>
</Select>
</Form.Item>
<Form.Item
noStyle
shouldUpdate={(prevValues, currentValues) => prevValues.gender !== currentValues.gender}
>
{({ getFieldValue }) => {
return getFieldValue('gender') === 'other' ? (
<Form.Item
name="customizeGender"
label="Customize Gender"
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
) : null;
}}
</Form.Item>
<Form.Item {...tailLayout}>
<Button type="primary" htmlType="submit">
Submit
</Button>
<Button htmlType="button" onClick={onReset}>
Reset
</Button>
<Button type="link" htmlType="button" onClick={onFill}>
Fill form
</Button>
</Form.Item>
</Form>
);
};
ReactDOM.render(<Demo />, document.getElementById('container'));
You can add an array of namePath in your form.resetFields call
const onReset = () => {
form.resetFields(["note"]);
};
Just tested it with your code and it works : https://stackblitz.com/edit/react-nazmet-jh2cc1?file=index.js
More info : https://ant.design/components/form/#FormInstance

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);

Disable form.item 1 if form.item 2 is filled in

I want to hide form.item 1 if form.item 2 is filled in and the other way around.
I want to do it for the following code but i cant find the solution to this.
<Form.Item label="Url">
{getFieldDecorator('url')(<Input/>)}
</Form.Item>
<Form.Item label="Standaard Urls" >
{getFieldDecorator('url_id', {})(this.getSelectUrls())}
</Form.Item>
Basically i want too know how i can hide 1 form.item and the rest i can do myself
You need to use onFieldsChange of Form.create, that keeps your Form uncontrollable which is the cleanest way.
Wrap your Form with a state, pass it and use onFieldsChange like so:
const FormContainer = () => {
const [isVisible, setIsVisible] = useState(true);
const onFieldsChange = (_, changedFiels) => {
const { password } = changedFiels;
if (password) {
console.log(`Now changing ${password.name}`);
setIsVisible(false);
}
};
const ValidatedFields = Form.create({ onFieldsChange })(MyForm);
return <ValidatedFields isVisible={isVisible} />;
};
Warning: You need to figure how you want to "remove" the form field, it depends on if you need its state or not, for this you can use display CSS property:
// Will unmount the item and lose it state
{ isVisible && <Form.Item>...}
// Will keep the state and hide the item
<Form.Item style={{ display: isVisible ? 'auto' : 'none' }}>...
Full code:
In this example, you can write in the password field and it will hide other forms items:
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import { Input, Form, Icon } from 'antd';
import 'antd/dist/antd.css';
import './index.css';
const FormContainer = () => {
const [isVisible, setIsVisible] = useState(true);
const onFieldsChange = (_, changedFiels) => {
const { password } = changedFiels;
if (password) {
console.log(`Now changing ${password.name}`);
setIsVisible(false);
}
};
const ValidatedFields = Form.create({ onFieldsChange })(MyForm);
return <ValidatedFields isVisible={isVisible} />;
};
const MyForm = ({ form, isVisible }) => {
const { getFieldDecorator, validateFields } = form;
const handleSubmit = e => {
e.preventDefault();
validateFields((err, values) => {
if (!err) {
console.log('Received values of form: ', values);
}
});
};
return (
<Form onSubmit={handleSubmit} className="login-form">
{isVisible && (
<Form.Item>
{getFieldDecorator('username', {
rules: [{ required: true, message: 'Please input your username!' }]
})(
<Input
prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
placeholder="Item 1"
/>
)}
</Form.Item>
)}
<Form.Item style={{ display: isVisible ? 'auto' : 'none' }}>
{getFieldDecorator('username2', {
rules: [{ required: true, message: 'Please input your username!' }]
})(
<Input
prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
placeholder="Item 2"
/>
)}
</Form.Item>
<Form.Item>
{getFieldDecorator('password', {
rules: [{ required: true, message: 'Please input your Password!' }]
})(
<Input
prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
type="password"
placeholder="Type here to hide other forms"
/>
)}
</Form.Item>
</Form>
);
};
ReactDOM.render(<FormContainer />, document.getElementById('root'));
const [showItem1, setShowItem1] = useState(true);
const [showItem2, setShowItem2] = useState(true);
onKeyPress = {() => {setShowItem1(true); setShowItem1(false); }}
onKeyPress = {() => {setShowItem1(false); setShowItem1(true); }}
{
showItem1 &&
<Form.Item label="Url">
{getFieldDecorator('url')(<Input/>)}
</Form.Item>
}
{
showItem2 &&
<Form.Item label="Standaard Urls" >
{getFieldDecorator('url_id', {})(this.getSelectUrls())}
</Form.Item>
}

Resources