Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const AddressList = (props) => {
- const [addresses, setAddresses] = React.useState(props.addresses);
- const handleAddRow = () => {
- let rows = [...addresses];
- rows.push(AddressModel);
- setAddresses(rows);
- };
- const handleRemoveRow = (index) => {
- let rows = [...addresses];
- rows.splice(index, 1);
- setAddresses(rows);
- };
- return (
- <React.Fragment>
- { addresses.map((address, index) =>
- <Address
- index={index}
- item={address}
- key={Math.random()}
- handleAddRow={handleAddRow}
- handleRemoveRow={handleRemoveRow}/>
- )}
- </React.Fragment>
- );
- };
- export default AddressList;
- const useStyles = makeStyles(theme => ({
- button: {
- margin: theme.spacing(1),
- },
- root: {
- display: 'inline-flex',
- maxWidth: 800,
- minWidth: 300,
- padding: 10,
- width: '100%'
- }
- }));
- const types = ['Home', 'Work'];
- const Address = (props) => {
- const classes = useStyles();
- // const [address, setAddress] = React.useState(props.item);
- const [address, setAddress] = useReducer((myArray, { type, value }) => {
- switch (type) {
- case "add":
- return [...myArray, value];
- case "remove":
- return myArray.filter((_, index) => index !== value);
- default:
- return myArray;
- }
- }, [address]);
- const handleAddressChange = name => event => {
- setAddress({ ...address, [name]: event.target.value });
- };
- const index = props.index;
- const handleAddRow = props.handleAddRow;
- const handleRemoveRow = props.handleRemoveRow;
- return (
- <Grid container className={classes.root} spacing={3}>
- <Grid item xs={12} sm={2}>
- <TextField
- id="type"
- label="Email Type"
- margin="normal"
- value={address.type}
- onChange={handleAddressChange('type')}
- fullWidth
- select>
- {types.map(option => (
- <MenuItem key={option} value={option}>{option}</MenuItem>
- ))}
- </TextField>
- </Grid>
- <Grid item xs={12} sm={9}>
- <TextField
- id="address"
- label="Address"
- margin="normal"
- value={address.address}
- onChange={handleAddressChange('address')}
- fullWidth
- required/>
- </Grid>
- <Grid item xs={12} sm={1}>
- {
- index === 0 ?
- <IconButton className={classes.button} aria-label="add" onClick={() => handleAddRow()}>
- <AddIcon/>
- </IconButton>
- :
- <IconButton className={classes.button} aria-label="delete" onClick={() => handleRemoveRow(index)}>
- <DeleteIcon/>
- </IconButton>
- }
- </Grid>
- </Grid>
- );
- };
- export default Address;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement