React Checkbox not getting value onCheck - reactjs

React Checkbox not getting value onCheck . I tried an accepted answer, and get constant value first , but it is getting undefined(data variable)
<TableCell>
<Checkbox name="myCheckBox1" onChange={(e, data) => this.checkchange1('2', data.value)}/>
</TableCell>
checkchange1 = (e, data) => {
console.log('it works');
console.log(data.value);
}
what am I missing ?

To get the value of checkbox, Try like below
<Checkbox name="myCheckBox1" value="checkedA" onChange={(e) => this.checkchange1(e)}/>
checkchange1 = (e) => {
console.log(e.target.value); /* checkedA will be consoled here */
}

onChange will take only one param and that is e.
you can store the value in state like this.
<Checkbox onChange={this.toggle} checked={this.state.checked} />
toggle = () => this.setState(({checked}) => ({ checked: !checked }))

Related

How do I checkbox checked/unchecked when I edit the record in react/redux

Code
const [checkedItems, setCheckedItems] = useState<any>(false)
<Checkbox
checked={checkedItems[condition?.condition_id]}
label="Pediatric"
onChange={(e) => {
handleCheckbox(
e,
condition?.condition_id,
'pediatric_flag'
)
}}
id={`conditionid-${condition?.id}`}
/>
const handleCheckbox = (e, conditionId, flag) => {
setCheckedItems({ ...checkedItems, [e.target.id]: e.target.checked })
}
I want to make checkboxes checked or unchecked based on getting data from APIs. Someone, please help me with this concern.

#material-ui Autocomplete: set input value programmatically

I have an asynchronous Autocomplete component that works fine so far.
Hopefully the simplified code is understandable enough:
export function AsyncAutocomplete<T>(props: AsyncAutocompleteProps<T>) {
const [open, setOpen] = useState(false);
const [options, setOptions] = useState<T[]>();
const onSearch = (search: string) => {
fetchOptions(search).then(setOptions);
};
return (
<Autocomplete<T>
open={open}
onOpen={() => {
setOpen(true);
}}
onClose={() => {
setOpen(false);
}}
onChange={(event, value) => {
props.onChange(value as T);
}}
getOptionSelected={props.getOptionSelected}
getOptionLabel={props.getOptionLabel}
options={options}
value={(props.value as NonNullable<T>) || undefined}
renderInput={(params) => (
<TextField
{...params}
onChange={(event) => onSearch(event.currentTarget.value)}
/>
)}
/>
);
}
The component above works easily: when the user clicks on the input, the Autocomplete component displays an empty input field where the user can type in a value to search for. After the input has changed, the options are refetched to show matching results.
Now I want to add support for shortcodes: when the user types qq, the search term should be replaced by something, just like if the user would have typed something himself.
However, I found no way to update the value of the rendered TextField programmatically. Even if I set value directly on the TextField, it won't show my value but only the users input.
So, any ideas how to solve this problem?
Thank you very much.
What I've tried so far was to simply update the input within onKeyUp:
// ...
renderInput={(params) => (
<TextInput
{...params}
label={props.label}
onChange={(event) => onSearchChange(event.currentTarget.value)}
InputProps={{
...params.InputProps,
onKeyUp: (event) => {
const value = event.currentTarget.value;
if(value === 'qq') {
event.currentTarget.value = 'something';
}
},
}}
/>
)}
With the code above I can see the something for a short time, but it gets replaced by the initial user input very soon.
Autocomplete is useful for setting the value of a single-line textbox in one of two types of scenarios: combobox and free solo.
combobox - The value for the textbox must be chosen from a predefined set.
You are using it so it not allowing you to add free text (onblur it replaced)
Answer: To take control of get and set value programmatically.
you need a state variable.
Check here codesandbox code sample taken from official doc
Your code with my comment:-
export function AsyncAutocomplete<T>(props: AsyncAutocompleteProps<T>) {
... //code removed for brevity
//This is a state variable to get and set text value programmatically.
const [value, setValue] = React.useState({name: (props.value as NonNullable<T>) || undefined});
return (
<Autocomplete<T>
... //code removed for brevity
//set value
value={value}
//get value
onChange={(event, newValue) => setValue(newValue)}
renderInput={(params) => (
<TextInput
{...params}
label={props.label}
onChange={(event) => onSearchChange(event.currentTarget.value)}
InputProps={{
...params.InputProps,
onKeyUp: (event) => {
//get value
const value = event.currentTarget.value;
//if qq then set 'something'
if (value === "qq") {
setValue({ name: "something" });
}
//otherwise set user free input text
else {
setValue({ name: value });
}
},
}}
/>
)}
/>
);
}

Can't access e.target.name

I have an application with different inputs. I want to access e.target.name of Switch, but i get undefined. For getting this i did:
const onChange = (name,e) => {
console.log(e.target.name)
}
and
<Switch defaultChecked onChange={e => onChange("test", e)} />
link to codesanbox: https://codesandbox.io/s/basic-usage-ant-design-demo-o3kro?file=/index.js:1198-1268
How to access Switch with e.target.name?
According to the docs(https://ant.design/components/switch/), I can see onChange takes the following format:
Function(checked: boolean, event: Event)
So In your code, you could pass the name attribute to your switch and access its current state(i.e checked) and also its event properties
const onChange = (checked, event) => {
console.log(checked, event.currentTarget.name);
};
<Switch defaultChecked name="test" onChange={onChange} />
The Switch component returns only trueor false.
If you do:
const onChange = (name,e) => {
console.log(e);
}
you can verify this.
If you want to acess the name "test" passed as argument, you just acess name parameter:
const onChange = (name,e) => {
console.log(name);
console.log(e);
}
**the switch return a boolean value on change **
const onChange = (name,checked) => {
console.log(checked)
}
and
<Switch defaultChecked onChange={checked => onChange("test", checked)} />

Setstate not updating in CustomInput type='checkbox' handler

This is the render method, how i am calling the handler and setting the reactstrap checkbox.
this.state.dishes.map(
(dish, i) => (
<div key={i}>
<CustomInput
type="checkbox"
id={i}
label={<strong>Dish Ready</strong>}
value={dish.ready}
checked={dish.ready}
onClick={e => this.onDishReady(i, e)}
/>
</div>))
The handler for the onClick listener, I've tried with onchange as well but it apears that onchange doesnt do anything, idk why?
onDishReady = (id, e) => {
console.log(e.target.value)
var tempArray = this.state.dishes.map((dish, i) => {
if (i === id) {
var temp = dish;
temp.ready = !e.target.value
return temp
}
else {
return dish
}
})
console.log(tempArray)
this.setState({
dishes: tempArray
});
}
The event.target.value isn't the "toggled" value of an input checkbox, but rather event.target.checked is.
onDishReady = index => e => {
const { checked } = e.target;
this.setState(prevState => {
const newDishes = [...prevState.dishes]; // spread in previous state
newDishes[index].ready = checked; // update index
return { dishes: newDishes };
});
};
The rendered CustomInput reduces to
<CustomInput
checked={dish.ready}
id={i}
label={<strong>DishReady</strong>}
onChange={this.onDishReady(i)}
type="checkbox"
/>
No need to pass in a value prop since it never changes.
Note: Although an onClick handler does appear to work, semantically it isn't quite the correct event, you want the logic to respond to the checked value of the checkbox changing versus a user clicking on its element.
You can do it this way:
this.setState(function (state) {
const dishes = [...state.dishes];
dishes[id].ready = !e.target.value;
return dishes;
});

Custom change handlers with inputs inside Formik

I'm porting some of my forms I made using SUIR over to a Formik implementation. I have input components that need custom change handlers to perform actions. How can I pass my change handler to the onChange prop so the values are tracked by formik?
I've tried something like this, but with no luck.
onChange={e => setFieldValue(dataSchemaName, e)}
which is mentioned in a different post here.
It's also mentioned here, but I can't quite get my custom change handler to hook up nicely with Formik.
My change handler looks like this
handleSchemaChange = (e, { value }) => {
this.setState({ dataSchemaName: value }, () => {
console.log("Chosen dataSchema ---> ", this.state.dataSchemaName);
//also send a request the selfUri of the selected dataSchema
});
const schema = this.state.dataschemas.find(schema => schema.name === value);
if (schema) {
axios
.get(schema.selfUri)
.then(response => {
console.log(response);
this.setState({
fields: response.data.data.fields,
});
console.log(this.state.fields);
})
.catch(error => console.log(error.response));
}
};
Here's an example of one of my form fields using a dropdown
<Form.Field>
<label style={{ display: "block" }}>
Select a Schema
</label>
<Dropdown
id="dataSchemaName"
multiple={false}
options={dataschemas.map(schema => {
return {
key: schema.id,
text: schema.name,
value: schema.name
};
})}
value={dataSchemaName}
onChange={this.handleSchemaChange}
/>
</Form.Field>
I have a sandbox with the issue
You can pass the setFieldValue function to your function handleSchemaChange and then use it inside.
So, instead of onChange={this.handleSchemaChange} make it
onChange={(e, val) => this.handleSchemaChange(e, val, setFieldValue)}.
And inside your handleSchemaChange function:
handleSchemaChange = (e, { value }, setFieldValue) => {
setFieldValue('dataSchemaName', value);
... the rest of your implementation
}
Here is a sandbox with the solution implemented:
https://codesandbox.io/s/formik-create-query-schema-uq35f

Resources