I don't know how to pass values from dropdown on select to 4 inputs. My dropdown showing address as it should be but I struggle to pass each value to separate inputs.e.g address_1 should be in one input where is flat number, address_2 where is street etc.
const [select,setSelect]=useState()
<select onChange={(e) => setSelect(e.target.value)}>
<option>Select Address</option>
{getAddressData?.address? (
getAddressData?.address?.map((address: any, id) => (
<option>{`${address.Address_1},${address.Address_2}, ${address.Town}, ${address.pafCounty}`}</option>
<input>
type={'text'}
name={'flatNumber'}
placeholder="Flat Number"
value={select}
</input>
Right now I have whole line of address e.g (30 Ballot Street,Smethick,West Midlands) in the whole one input.
CodePudding user response:
Instead of setSelect(e.target.value)
, set it to the original structured address object. You could have the value of the option be the index within the address list, for example, and then setSelect(getAddressData?.address[2])
or whatever.
CodePudding user response:
Here's the working code. It's live here: https://codesandbox.io/s/competent-firefly-0qdrij?file=/src/App.js
import React, { useState, useEffect } from "react";
function App() {
const [address, setAddress] = useState({
Address_1: "",
Address_2: "",
Town: "",
pafCounty: ""
});
let getAddressData = {};
getAddressData.address = [
{
Address_1: "Address_1",
Address_2: "Address_2",
Town: "Town",
pafCounty: "pafCounty"
},
{
Address_1: "Address_11",
Address_2: "Address_22",
Town: "Town2",
pafCounty: "pafCounty2"
}
];
function handleChange(e) {
setAddress({ ...address, [e.target.name]: e.target.value });
}
useEffect(() => {
console.log(address);
}, [address]);
return (
<>
<select
onChange={(e) => {
setAddress(getAddressData?.address[e.target.value]);
}}
>
<option selected disabled>
Select Address
</option>
{getAddressData?.address?.map((address, index) => (
<option
key={index}
value={index}
>{`${address.Address_1}, ${address.Address_2}, ${address.Town}, ${address.pafCounty}`}</option>
))}
</select>
{Object.keys(address).map((key, index) => (
<input
type="text"
name={key}
placeholder="Flat Number"
value={address[key]}
onChange={handleChange}
/>
))}
</>
);
}
export default App;