React TextField with collapse - javascript

How to hide the lists of cities when the textfield is empty and when the user start typing the lists will show.
https://codesandbox.io/s/loving-platform-t2cyb?file=/src/LocationWidget.js
const openSearch = () => {
setViewLocationList(true);
startSearch();
};
const stopSearch = () => {
setSearchParameter('')
setViewLocationList(false);
};
<TextField
variant="outlined"
placeholder="Search Locations"
onFocus={openSearch}
onChange={filterResults}
value={searchParameter}
classes={{notchedOutline:classes.input}}
InputProps={{
endAdornment: (
<IconButton onClick={stopSearch} edge="end">
<ClearIcon />
</IconButton>
),
classes:{notchedOutline:classes.noBorder},
startAdornment: (
<InputAdornment position="start">
<SearchIcon />
</InputAdornment>
),
}}
/>
</Box>
<Collapse in={viewLocationList} sx={{ my: '2px' }}>
<Box className="rounded-scrollbar widget-result-container">
{filteredLocations.map((location, index) => (
<LocationWidgetItem
key={index}
location={location}
onClickLocation={setActiveLocation}
/>
))}
</Box>
</Collapse>

You have to take state variable in which you have to store whatever user is typing:
const [text,setText] = useState("");
and in your filterLocations you have to update its value
const filterLocations = (txt) => {
setText(txt.target.value);
let filteredLocations = locations.filter((e) =>
e.name.toLowerCase().includes(txt.target.value.toLowerCase())
);
setSearchParameter(filteredLocations);
};
And Finally in your render, render ul conditioanlly
{ !!text && <ul>
{searchParameter.map((location) => (
<li key={location.name}>{location.name}</li>
))}
</ul>}
https://codesandbox.io/s/dreamy-roentgen-0jnoi?file=/src/LocationWidget.js

please find below code.
export default function LocationWidget({ locations }) {
const [searchParameter, setSearchParameter] = useState(locations);
const [inputText, setInputText] = useState(null);
const filterLocations = (txt) => {
setInputText(txt.target.value);
let filteredLocations = locations.filter((e) =>
e.name.toLowerCase().includes(txt.target.value.toLowerCase())
);
setSearchParameter(filteredLocations);
};
return (
<>
<input type="text" onChange={filterLocations} />
{inputText && <ul>
{searchParameter.map((location) => (
<li key={location.name}>{location.name}</li>
))}
</ul>}
</>
);
}

You'd like to set an 'input' eventListener on the input field. And check if the inputField length > 0, then set the setViewLocationList(true); and if the inputField length === 0, then set the setViewLocationList(false).

Related

Return the same Div when clicking + button in React JS

i build this div element here , which at the end has a "+" button and a "x" button . The plus button adds the same div just below it and the x or clear button removes it . Now how can i render the same div when clicking plus button or when clicking x , i tried multiple ways but i couldn't do it , this is my code. One way that i think of is doing recursion but it doesn't work.
function IpRangeInput() {
const [ipRange, setIpRange] = useState<string>('');
const [inputValue, setInputValue] = useState<string>('');
const [fromValue, setFromValue] = useState<string>('');
const [toValue, setToValue] = useState<string>('');
const handleInputValue = (event: React.ChangeEvent<HTMLInputElement>) => {
setInputValue(event?.target.value);
};
const handleAdd = () => <IpRangeInput />;
return (
<Box className={styles.inputContainer}>
<ThemeProvider theme={theme}>
<FormControl className={styles.inputContainer__select}>
<Select
defaultValue="Select"
id="select-label"
value={ipRange}
onChange={(e) => setIpRange(e.target.value)}
>
<MenuItem value="IP/CIDR">IP / CIDR</MenuItem>
<MenuItem value="Range">Range</MenuItem>
</Select>
</FormControl>
{ipRange === 'Range' ? (
<>
<span className={styles.inputContainer__text}>From</span>
<Box
className={[
styles.inputContainer__input,
styles.inputContainer__newInput,
].join(' ')}
>
<TextField
value={fromValue}
onChange={(e) => setFromValue(e.target.value)}
/>
</Box>
<span className={styles.inputContainer__text}>To</span>
<Box
className={[
styles.inputContainer__input,
styles.inputContainer__newInput,
].join(' ')}
>
<TextField
value={toValue}
onChange={(e) => setToValue(e.target.value)}
/>
</Box>
</>
) : (
<Box className={styles.inputContainer__input}>
<TextField value={inputValue} onChange={handleInputValue} />
</Box>
)}
<IconButton
className={styles.inputContainer__addButton}
onClick={handleAdd}
>
<AddIcon />
</IconButton>
<IconButton
className={styles.inputContainer__clearButton}
onClick={handleAdd}
>
<Clear />
</IconButton>
</ThemeProvider>
</Box>
);
}
<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>
Вам нужно хранить список блоков в родительском компоненте в стейте, например, как массив айди. Каждому блоку присваивается свой айди. И в итоге нажатие кнопок будет триггерить удаление или добавление айди в массив или из него
Ваш итоговый код:
function Parent () {
const [list, setList] = useState([0])
const handleAdd = (id) => setList(prevList => prevList.push(id + 1))
const handleClear = (id) => setList(prevList => {
prevList.splice(id, 1)
return prevList
})
return (
list.map((item) => {
<IpRangeInput
key={item}
id={item}
handleAdd={handleAdd}
handleClear={handleClear}
/>
})
)
}
function IpRangeInput({ handleAdd, handleClear, id }) {
const [ipRange, setIpRange] = useState<string>('');
const [inputValue, setInputValue] = useState<string>('');
const [fromValue, setFromValue] = useState<string>('');
const [toValue, setToValue] = useState<string>('');
const handleInputValue = (event: React.ChangeEvent<HTMLInputElement>) => {
setInputValue(event?.target.value);
};
const handleAdd = () => handleAdd(id)
const handleClear = () => handleAdd(id)
return (
<Box className={styles.inputContainer}>
<ThemeProvider theme={theme}>
<FormControl className={styles.inputContainer__select}>
<Select
defaultValue="Select"
id="select-label"
value={ipRange}
onChange={(e) => setIpRange(e.target.value)}
>
<MenuItem value="IP/CIDR">IP / CIDR</MenuItem>
<MenuItem value="Range">Range</MenuItem>
</Select>
</FormControl>
{ipRange === 'Range' ? (
<>
<span className={styles.inputContainer__text}>From</span>
<Box
className={[
styles.inputContainer__input,
styles.inputContainer__newInput,
].join(' ')}
>
<TextField
value={fromValue}
onChange={(e) => setFromValue(e.target.value)}
/>
</Box>
<span className={styles.inputContainer__text}>To</span>
<Box
className={[
styles.inputContainer__input,
styles.inputContainer__newInput,
].join(' ')}
>
<TextField
value={toValue}
onChange={(e) => setToValue(e.target.value)}
/>
</Box>
</>
) : (
<Box className={styles.inputContainer__input}>
<TextField value={inputValue} onChange={handleInputValue} />
</Box>
)}
<IconButton
className={styles.inputContainer__addButton}
onClick={handleAdd}
>
<AddIcon />
</IconButton>
<IconButton
className={styles.inputContainer__clearButton}
onClick={handleClear}
>
<Clear />
</IconButton>
</ThemeProvider>
</Box>
);
}

Cant Edit dynamic Textfield form graphql data in reactjs

I'm trying to create a dynamic textfield that takes data from gql like this
const { data } = useQuery(DATA_LIST, {
variables: {
param: {
limit: 10,
offset: 0,
sortBy: 'order'
}
}
});
const [state, setState] = useState<any>([]);
useEffect(() => {
if (data) {
setState(data?.dataList?.data);
}}, [data]);
then create a textField like this :
<TextField
name="name"
required
fullWidth
// label="Status Name"
onChange={(event) => handleChange(event, index)}
value={item?.name}
sx={{ marginRight: 5 }}
/>
<TextField
name="category"
required
fullWidth
select
// label="Category"
onChange={(event) => handleChange(event, index)}
value={item?.category}
>
{Category.map((option, index) => (
<MenuItem key={index} value={option.value}>
{option.name}
</MenuItem>
))}
</TextField>
handleChange :
const handleChangeInput = (
event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
index: number
) => {
const values = [...state];
values[index][event.target.name] = event.target.value;
console.log(values[index], 'ini values');
setState(values);
};
and call the inputRow component like this (im using drag and drop for textField list) :
{state.map((item: any, index: any) => {
// console.log(statusName[index]);
return (
<Draggable key={item.id} draggableId={String(item.id)} index={index}>
{(provided, snapshot): JSX.Element => (
<div
key={index}
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
style={getItemStyle(snapshot.isDragging, provided.draggableProps.style)}
>
<Box marginRight={2}>
<TypographyComponent text={index + 1} type={'subBody'} />
</Box>
<InputRow index={index} item={item} handleChange={handleChangeInput} />
</div>
)}
</Draggable>
);
})}
but when i try to type the textfield, an error appears that Cannot assign to read only property
error message
This is weird because if I input dummy data, the textfield can be modified, but if I use data from the API the data cannot be modified.

Is rendering the Autocomplete options list with column headers possible?

I would like to know if it is possible to customise the above example so that the list would have column headers such as Title and duration. I have tried to see if I could get it to work using a custom ListBox, but no such luck. Below is a snippet of my own code:
const PopperMy = function (props: PopperProps) {
return <Popper {...props} style={{ width: 500 }} placement='bottom-start' />;
};
return (
<Autocomplete
filterOptions={(x) => x}
getOptionLabel={(option: Record<string, unknown>) => `${option.order}, ${option.name}, ${option.email}, ${option.phone}, ${option.location}`}
renderOption={(props, option: any) => {
return (
<li {...props} key={option.ID} >
Order: {option.order}, Name: {option.name}, Email: {option.email}, Phone: {option.phone}, Location: {option.location}, Status: {option.status}
</li>
);
}}
options={results}
value={selectedValue}
clearOnBlur={false}
freeSolo
PopperComponent={PopperMy}
disableClearable={true}
includeInputInList
onChange={(ev, newValue) => {
setSelectedValue(newValue);
}}
onInputChange={(ev, newInputValue) => {
setInputValue(newInputValue);
}}
renderInput={(params) => (
<TextField {...params} />
)} /> )
this is achievable by customizing the popper component. In your case, something like `
const PopperMy = function (props) {
const { children, ...rest } = props;
return (
<Popper {...rest} placement="bottom-start">
<Box display="flex" justifyContent="space-between" px="16px">
<Typography variant="h6">Title</Typography>
<Typography variant="h6">Year</Typography>
........... rest of the titles
</Box>
{props.children}
</Popper>
);
};
`
would work. Here is a working example i have created - https://codesandbox.io/s/heuristic-golick-4sv24u?file=/src/App.js:252-614

React - Close MUI drawer from nested menu

I'm using this excellent example (Nested sidebar menu with material ui and Reactjs) to build a dynamic nested menu for my application. On top of that I'm trying to go one step further and put it into a Material UI appbar/temporary drawer. What I'd like to achieve is closing the drawer when the user clicks on one of the lowest level item (SingleLevel) however I'm having a tough time passing the toggleDrawer function down to the menu. When I handle the click at SingleLevel I consistently get a 'toggle is not a function' error.
I'm relatively new to this so I'm sure it's something easy and obvious. Many thanks for any answers/comments.
EDIT: Here's a sandbox link
https://codesandbox.io/s/temporarydrawer-material-demo-forked-v11ur
Code is as follows:
Appbar.js
export default function AppBar(props) {
const [drawerstate, setDrawerstate] = React.useState(false);
const toggleDrawer = (state, isopen) => (event) => {
if (event.type === 'keydown' && (event.key === 'Tab' || event.key === 'Shift')) {
return;
}
setDrawerstate({ ...state, left: isopen });
};
return (
<Box sx={{ flexGrow: 1 }}>
<AppBar position="static" color="secondary">
<Toolbar>
<IconButton
size="large"
edge="start"
color="primary"
aria-label="menu"
onClick={toggleDrawer('left', true)}
>
<MenuIcon />
</IconButton>
<img src={logo} alt="logo" />
</Toolbar>
<Drawer
anchor='left'
open={drawerstate['left']}
onClose={toggleDrawer('left', false)}
>
<Box>
<AppMenu toggleDrawer={toggleDrawer} />
</Box>
</Drawer>
</AppBar>
</Box >
)
}
Menu.js
export default function AppMenu(props) {
return MenuItemsJSON.map((item, key) => <MenuItem key={key} item={item} toggleDrawer={props.toggleDrawer} />);
}
const MenuItem = ({ item, toggleDrawer }) => {
const MenuComponent = hasChildren(item) ? MultiLevel : SingleLevel;
return <MenuComponent item={item} toggleDrawer={toggleDrawer} />;
};
const SingleLevel = ({ item, toggleDrawer }) => {
const [toggle, setToggle] = React.useState(toggleDrawer);
return (
<ListItem button onClick={() => { toggle('left', false) }}>
<ListItemIcon>{item.icon}</ListItemIcon>
<ListItemText primary={item.title} />
</ListItem>
);
};
const MultiLevel = ({ item }) => {
const { items: children } = item;
const [open, setOpen] = useState(false);
const handleClick = () => {
setOpen((prev) => !prev);
};
return (
<React.Fragment>
<ListItem button onClick={handleClick}>
<ListItemIcon>{item.icon}</ListItemIcon>
<ListItemText primary={item.title} secondary={item.description} />
{open ? <ExpandLess /> : <ExpandMore />}
</ListItem>
<Collapse in={open} timeout="auto" unmountOnExit>
<List component="div" disablePadding>
{children.map((child, key) => (
<MenuItem key={key} item={child} />
))}
</List>
</Collapse>
</React.Fragment>
);
};
You shouldn't call a react hook inside of any function that is not a react component. Please see React Rules of Hooks
What you could do instead is pass setToggle directly into the Drawer component as a prop and do something like this for it's onClick attribute:
onClick={() => setToggle(<value>)}

Material-UI TextField loses focus on every onChange

I am creating the following component:
It will contain an array of objects, where each object is a prescription, with the medicine name from the select and a TextField for the Dosis.
My problem is that the TextField loses focus on every onChange() and is very frustrating because it cannot be edited on a single focus.
This is my component :
const MedicineSelect = ({ medications, setMedications, ...props }) => {
const { medicines } = useMedicines()
const classes = useStyles()
const handleChange = (index, target) => {
// setAge(event.target.value)
const newMedications = cloneDeep(medications)
newMedications[index][target.name] = target.value
setMedications(newMedications)
}
const handleAddMedicine = () => {
const newMedications = cloneDeep(medications)
newMedications.push({ medicine: '', dosis: '', time: '' })
setMedications(newMedications)
}
const handleDeleteMedicine = (index) => {
console.log('DELETE: ', index)
const newMedications = cloneDeep(medications)
newMedications.splice(index, 1)
setMedications(newMedications)
}
return (
<Paper style={{ padding: 5 }}>
<List>
{medications.map((medication, index) => (
<ListItem key={nanoid()} divider alignItems='center'>
<ListItemIcon>
<Tooltip title='Eliminar'>
<IconButton
className={classes.iconButton}
onClick={() => handleDeleteMedicine(index)}
>
<HighlightOffOutlinedIcon />
</IconButton>
</Tooltip>
</ListItemIcon>
<FormControl className={classes.formControl}>
<InputLabel
id={`${index}-select-${medication}-label`}
>
Medicamento
</InputLabel>
<Select
labelId={`${index}-select-${medication}-label`}
id={`${index}-select-${medication}`}
name='medicine'
value={medication.medicine}
onChange={(event) =>
handleChange(index, event.target)
}
>
{medicines.map((medicine) => (
<MenuItem
key={nanoid()}
value={medicine.name}
>
{medicine.name}
</MenuItem>
))}
</Select>
</FormControl>
<TextField
// fullWidth
id={`${index}-text-${medication}`}
label='Dosis'
name='dosis'
onChange={(event) =>
handleChange(index, event.target)
}
value={medication.dosis}
/>
</ListItem>
))}
<Button onClick={handleAddMedicine}>+ agregar</Button>
</List>
</Paper>
)
}
And here is where I set the component:
const [medications, setMedications] = useState([
{ medicine: '', dosis: '', time: '' },
])
...
<Grid item md={12} xs={12}>
<Accordion>
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
aria-controls='panel1a-content'
id='panel1a-header'
>
<Typography variant='h4'>
Tratamiento:
</Typography>
</AccordionSummary>
<AccordionDetails>
<Container disableGutters>
<MedicineSelect
medications={medications}
setMedications={setMedications}
/>
</Container>
</AccordionDetails>
</Accordion>
</Grid>
...
Adding and removing objects from the array works perfect. selecting the medicine from the select, also works perfect. the only problem I have is when editing the Dosis TextField, with every character, the focus is lost and I have to click again on the TextField.
Please help me getting this fixed!!!
After searching a lot, finally I found the solution. Actually when using nanoid() to create unique keys, on every state update React re-renders all components and since the id of both the List and the TextField component are regenerated by nanoid on every render, React loses track of the original values, that is why Focus was lost.
What I did was keeping the keys unmuttable:
<ListItem key={`medication-${index}`} divider alignItems='center'>
and
<TextField
key={`dosis-${index}`}
fullWidth
// id={`${index}-dosis-${medication}`}
label='Dosis'
name='dosis'
onChange={(event) =>
handleChange(index, event.target)
}
value={medication.dosis}
/>

Categories

Resources