Passing a text field value on a button click - javascript

Here is the code that contains the text field and the button. I want to call the "apiFetcher" function with the value of the text field. I commented out the onblur function in the text field. That worked perfectly fine. Any suggestions to fix this issue.
<Autocomplete
id="free-solo-2-demo"
disableClearable
options={Cities.map((option) => option.name)}
renderInput={(params) => (
<div
>
<TextField
id="standard-basic"
{...params}
label="city"
margin="normal"
InputProps={{ ...params.InputProps, type: 'search' }}
// onBlur={apiFtecher}
/>
</div>
)}
/>
</Grid>
<Grid className={classes.seIcon} item xs={1}>
<div onClick={apiFtecher}>
<IconButton>
<SearchIcon/>
</IconButton>
</div>
</Grid>
Here is the apiFetcher function
const apiFtecher = e => {
setcity(e.target.value);
console.log(city);
}

Here is what i did
const [town,settown]=useState("");
function APIsetter(){
return(
setcity(town)
)
}
And then bind the APIsetter to onclick function of the button.And it worked

Related

Unable to disable keyboard date change in MUI DatePicker API

Link to CodeSandBox : codesandbox.io/s/dl5jft?file=/demo.tsx
I don't want users to Edit dates via keyboard, I want them to select dates from date picker modal, how to disable this?,
i used the ReadOnly prop but it is disabling date selection itself, please help when i did readOnly, it is disabling the whole input, which made me unable to open the modal to select the date
<GlobalStyle />
<CalendarContainer>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
value={calendarVal}
onChange={(newValue) => {
handleChange(newValue);
}}
disabled={disabled}
inputFormat="dd-MM-yyyy"
renderInput={(params) => (
<TextField
// eslint-disable-next-line react/jsx-props-no-spreading
{...params}
name={name}
error={error}
disabled={disabled}
/>
)}
/>
</LocalizationProvider>
</CalendarContainer>
For preventing user keyboard actions, you can set the functionality of onKeyDown event to preventDefault and assign it to TextField:
const onKeyDown = (e) => {
e.preventDefault();
};
return (
<LocalizationProvider dateAdapter={AdapterDateFns}>
<Stack spacing={3}>
<DesktopDatePicker
label="Date desktop"
inputFormat="MM/dd/yyyy"
value={value}
onChange={handleChange}
renderInput={(params) => (
<TextField onKeyDown={onKeyDown} {...params} />
)}
/>
)
For me, in latest #mui 5, the other solutions weren't working properly.
The only solution that worked for me is:
<DatePicker
dateAdapter={AdapterDateFns}
renderInput={(params) => (
<TextField
{...params}
inputProps={{...params.inputProps, readOnly: true}}
/>
)}
/>
I have done 2 things to solve this:
1- set render input TextField to readOnly => no typing
2- add sx of TextField caretColor: 'transparent' => hide the caret
<DatePicker
renderInput={params => (
<TextField
{...params}
InputProps={{
readOnly: true,
sx={{
"& .MuiInputBase-input": {
caretColor: 'transparent'
}
}}
/>
)}
/>

The reason why clicking on one checkbox deactivates the entire input

I'm facing a problem that I seem to know but I don't know. I made "State" by [checked]. There is a problem that if you turn this to the map and click only one checkbox, the whole is clicked. So I put {cked[idx]} to solve it, but my senior advised me that there was a problem with the code.
Because [checked] is in the form of "Boolean" and idx is "number".
And input has a 'disabled' attribute. I know that this is also deactivated as a whole because I put 'checked' in. By the way, I want each of them to be deactivated when I press the check box. But I don't know how. I searched for stack overflow, but I couldn't find a similar case to mine.
I believe you guys can help me.
const [checked, setChecked] = useState(false);
.
.
.
{keys &&
keys?.map((item: any, idx: number) => {
return (
<div key={idx}>
<Box component="form" className={classes.Box}>
<div className={classes.typeText}>{item.columnName}</div>
<div className={classes.flexWrap}>
<TextField
id="outlined-basic"
label={item.type}
variant="outlined"
className={classes.filled}
disabled={checked} //hear❗️
/>
<FormControlLabel
value="end"
control={
<Checkbox
className={classes.checkBox}
color="primary"
checked={checked[idx]} //hear❗️
onChange={handleCheckboxChange}
/>
}
label="Null"
labelPlacement="end"
/>
</div>
</Box>
</div>
);
})}
Move your textfield and checkbox to a different component so each one can have its own state.
function CheckComponent = (item, handleCheckboxChange) => {
const [checked, setChecked] = useState(false);
return (
<Box component="form" className={classes.Box}>
<div className={classes.typeText}>{item.columnName}</div>
<div className={classes.flexWrap}>
<TextField
id="outlined-basic"
label={item.type}
variant="outlined"
className={classes.filled}
disabled={checked}
/>
<FormControlLabel
value="end"
control={
<Checkbox
className={classes.checkBox}
color="primary"
checked={checked}
onChange={handleCheckboxChange}
/>
}
label="Null"
labelPlacement="end"
/>
</div>
</Box>
);
}
Then render as many as you need
{keys && keys?.map((item: any, idx: number) => {
<CheckComponent key={idx} item={item} handleCheckboxChange={() => console.log("clicked", idx); } />
})}
Something along these lines.

Is there a way to change the close icons on the autocomplete component of material ui?

I would like to change the icon, but would like to keep the function when clicking.
is there a good solution for this?
I want to change this Icon
<Autocomplete
multiple
id="checkboxes-tags-demo"
options={top100Films}
disableCloseOnSelect
getOptionLabel={(option) => option.title}
renderOption={(option, { selected }) => (
<React.Fragment>
<Checkbox
icon={icon}
checkedIcon={checkedIcon}
style={{ marginRight: 8 }}
checked={selected}
/>
{option.title}
</React.Fragment>
)}
style={{ width: 500 }}
renderInput={(params) => (
<TextField {...params} variant="outlined" label="Checkboxes" placeholder="Favorites" />
)}
/>
Can anybody help me?
You can pass a function to customize the rendering of the Chip component used by the Autocomplete
<Autocomplete
multiple
id="tags-filled"
options={top100Films.map((option) => option.title)}
defaultValue={[top100Films[13].title]}
freeSolo
renderTags={(value, getTagProps) =>
value.map((option, index) => (
<Chip variant="outlined" label={option} {...getTagProps({ index })} />
))
}
renderInput={(params) => (
<TextField {...params} variant="filled" label="freeSolo" placeholder="Favorites" />
)}
/>
And the Chip component can be further customized with the deleteIcon prop
Edit: For more info, see the API of the Autocomplete and the API of the Chip
You can change it using the ChipProps of Autocomplete, as that icon is a part of a Chip component, and can be customized through deleteIcon property

Material UI <Autocomplete/> remove browser suggestion

I have problem with Material-ui Autocomplete:
import Autocomplete from "#material-ui/lab/Autocomplete";
I am using then in:
<Autocomplete
id="checkboxes-tags-demo"
autoComplete={false}
options={states}
disableCloseOnSelect
getOptionLabel={(option) => option.name}
onChange={onStateChange}
renderOption={(option, { selected }) => (
<React.Fragment>
<Checkbox
icon={icon}
checkedIcon={checkedIcon}
style={{ marginRight: 8 }}
checked={selected}
/>
{option.name}
</React.Fragment>
)}
style={{ width: "100%" }}
renderInput={(params) => (
<TextField
{...params}
variant="outlined"
label="State"
placeholder="Enter state"
/>
)}
/>
Nothing important in this code but I face this issue:
I am getting the browser suggestion. How I can remove it ?
As mentioned in this SO question, you should add autoComplete="off" to your TextField.

React Button unable to call method in Function component

I have a React button that is a form and I intend to submit the form when I click on the Button. Unfortunately, when I click on the button, nothing happens and the page only reloads. Even when I just try to output to the console nothing happens but when you check the network, you could see an action being performed.
Below is my code which is just a simple login form and a functionality that validates user input. I need the button to call the function handleSubmit when I click on the button.
export default function Signin() {
const classes = useStyles();
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [usernameError, setUsernameError] = useState('');
const [passwordError, setPasswordError] = useState('');
const validateUsername = () => {
setUsernameError(username.length > 3 ? null : 'Username must be longer than 3 characters')
}
const validatePassword = () => {
setPasswordError(password.length > 7 ? null : 'Password must be longer than 8 characters')
}
const handleSubmit = () => {
//const { history } = this.props;
console.log('testing button')
}
return (
<Grid
className={classes.root}
component="main"
container
>
<CssBaseline />
<Grid
className={classes.image}
item
md={4}
sm={7}
xs={false}
/>
<Grid
component={Paper}
elevation={6}
item
md={8}
sm={5}
square
xs={12}
>
<MuiThemeProvider theme={theme}>
<div className={classes.paper}>
<img
alt="logo"
src={process.env.PUBLIC_URL + '/images/....'}
/>
<Typography
component="h1"
style={{ color: '#E60000' }}
variant="h5"
>
Sign In
</Typography>
<form
className={classes.form}
noValidate
>
<Grid
container
spacing={2}
>
<Grid
item
xs={3}
/>
<Grid
item
xs={6}
>
<TextField
autoComplete="username"
className={`form-control ${usernameError ? 'is-invalid' : ''}`}
fullWidth
id="username"
label="Enter Username"
margin="normal"
name="username"
onBlur={validateUsername}
onChange={e => setUsername(e.target.value)}
required
value={username}
variant="outlined"
/>
<div className={classes.invalidFeedback}>{usernameError}</div>
</Grid>
<Grid
item
xs={3}
/>
<Grid
item
xs={3}
/>
<Grid
item
xs={6}
>
<TextField
autoComplete="current-password"
className={`form-control ${passwordError ? 'is-invalid' : ''}`}
fullWidth
id="password"
label="Password"
margin="normal"
name="password"
onBlur={validatePassword}
onChange={e => setPassword(e.target.value)}
required
type="password"
value={password}
variant="outlined"
/>
<div className={classes.invalidFeedback}>{passwordError}</div>
</Grid>
<Grid
item
xs={3}
/>
<Grid
item
xs={3}
/>
<Grid
item
xs={3}
>
<Button
className={classes.submit}
color="primary"
fullWidth
onClick={handleSubmit}
type="submit"
variant="contained"
>
Sign In
</Button>
<Grid
item
xs={3}
/>
</Grid>
</Grid>
<Grid container>
<Grid
item
xs={3}
/>
<Grid
item
xs={3}
>
<Link
className={classes.link}
to={`${process.env.PUBLIC_URL}/passwordreset`}
variant="body2"
>
<Button
className={classes.submit}
color="primary"
fullWidth
type="submit"
variant="text"
>
Forgot Password
</Button>
</Link>
</Grid>
<Grid item>
<Link
className={classes.link}
to={`${process.env.PUBLIC_URL}/signup`}
variant="body2"
>
<Button
className={classes.submit}
color="primary"
fullWidth
type="submit"
variant="text"
>
New User?
</Button>
</Link>
</Grid>
</Grid>
<Box mt={5}>
<SigninTrouble />
</Box>
</form>
</div>
</MuiThemeProvider>
</Grid>
</Grid>
);
}
Since you are using Form you need to handle submit method in form instead of your button. Because your button type is submit which triggers the onSubmit event in form.
<form onSubmit={handleSubmit}>
<button type="submit"></button>
</form>
If you want to make an async call you need to stop normal event cycle for your form.
const handleSubmit = (event) => {
// stop redirect
event.preventDefault();
console.log('testing button');
// here you can make your async call
}
In order to use a button with type submit it has to be nested within an html form tag and handle the submission with the onsubmit attribute.
Onother option is to attack an onClick event handler to your button and have your submission logic there.
Here is very simple example:
import React, {useEffect, useState} from 'react';
function Example(props) {
function clickHandler() {
alert('hi');
}
return (
<div>
<button onClick={clickHandler}>Click here</button>
</div>
);
}
export default Example;

Categories