How to get the value from the react fabric ui checkbox - javascript

This is the JSX tag. I'm getting the status of the checkbox but not the value or the label name.
<Checkbox label="Innovation" value="Innovation" onChange={this._onChange} />
Below is the code that shows the status
public _onChange(ev: React.FormEvent<HTMLElement>, isChecked: boolean) {
console.log(`The option has been changed to ${isChecked}.`);
I tried to pass the value but it didn't work.

You should use Checkbox tag inside Stack tag like this
<Stack>
<Checkbox label="Innovation" onChange={_onChange} />
</Stack>
function _onChange(ev: React.FormEvent<HTMLElement>, isChecked: boolean) {
console.log(`The option has been changed to ${isChecked}.`);
}
For more reference you can go through this link

You can consider using the inputProps attribute to set the value and id of the element.
After you set the value and id of the element, then in the onChangeEvent, you can read these values from event object
<FabricCheckbox ...props inputProps={{value:myVal, id:myId}} onChange={(e, checked) => this.handleOnChange}/>
...
handleOnChange(event, checked) {
const selectedVal = event.target.value; //This will return the value you set
}

Related

Get a checkbox value on change of other checkbox in react

I have 2 checkboxes A and B. I want to check whether checkbox B is checked or not on change of checkbox A and vice versa. Also I want to change checkbox B on change of checkbox A. How can we achieve that in react.js.
You can create a state for both of them and change it accordingly.
This way you'll have access to it whenever needed.
Also, to avoid handling changes separately for every input, you can give each of them a name and then have a single dedicated function that changes the value of the checkbox based on it's name.
Example:
function App() {
const [state, setState] = useState({
firstCheckbox: false,
secondCheckbox: false,
})
const handleChange = (e) => {
setState(prev => ({
...prev,
[e.currentTarget.name]: e.currentTarget.checked,
}));
};
return (
<>
<input
name='firstCheckbox'
type='checkbox'
checked={state.firstCheckbox}
onChange={handleChange}
/>
<input
name='secondCheckbox'
type='checkbox'
checked={state.secondCheckbox}
onChange={handleChange}
/>
</>
)
}
Currently in this example, each checkbox relates to it's own state.
However, you can easily adjust the handleChange function based on your needs.

Input radio button's defaultChecked attribute prevents onClick function from being triggered

<section key={i}>
<input
type='radio'
key={attribute.name + item.id}
id={attribute.name + item.id}
name={attribute.name}
value={item.value}
defaultChecked={i === 0}
onClick={(event) => inputClick(attribute, event)}
/>
<label
htmlFor={attribute.name + item.id}
>
{
item.value
}
</label>
</section>
The code above is more or less what a .map() function is supposed to return in my React.js APP, creating input radio buttons for customizing a product before adding it to the cart state. All I did was remove some classes, etc. that were there for CSS purposes, etc.
Ideally, what is supposed to happen here is that...
When rendering the product page for the first time, the very first input radio button that is returned by .map() should be checked by default. This works thanks to the "defaultChecked" attribute. No problems here.
After I click a different input radio button (not the "defaultChecked" one), the checked input should change and all the other inputs should be left unchecked. As I understand it, input radio buttons with the same 'name' attribute do this automatically.
When clicking the input radio button, the "onClick" function should trigger. This is where the code is not functioning as I wish it would.
The issue is that when my page renders for the first time and I click on an input radio button (other than the "defaultChecked") the "onClick" function does not trigger. It only triggers when I have clicked on a different input once and then on another.
A.k.a. it triggers on the second click. After that second click, it works as intended - every time a different input radio button is selected/clicked on - the function triggers, but not for the very first time.
I tested this with console.log("I am triggered") at the end of the "onClick" "inputClick(attribute, event)" function, and only on the second click would the console log "I am triggered".
I was able to fix the issue by removing the "defaultChecked" attribute. I think the issue might be tied to the fact that the "onClick" function is only able to be triggered when one input gains the "checked" attribute and another loses it, but the "defaultChecked" attribute does not count as an input being "fully checked" or something like that.
I could leave it at that, but the project that I am working on required me to have a default checked input radio button on the first-page render. So, I can't just delete the "defaultChecked" attribute and call it a day.
Any ideas on what could be causing this behavior?
UPDATE1
The following is the body of the inputclick() function:
//* Handle input selection
const inputClick = (attribute, event) => {
//* Parse state
let state = JSON.parse(JSON.stringify(itemState));
//* Get all the required values from the clicked input
const attributeId = attribute.id;
const itemTargetValue = event.target.value;
//* Check if the attribute is in state
const attributeIs = state.some(item => item.id === attributeId);
//* If the attribute does not exsist - add the attribute to state
if(attributeIs === false) {
const obj = {
id: attributeId,
selectedItem: itemTargetValue
};
state.push(obj);
return setitemState(state);
}
//* If the attribute id already exsists in state
if(attributeIs) {
//* Find the index of the attribute in question
const attributeIndex = state.map(object => object.id).indexOf(attributeId);
const attributeInQuestion = state[attributeIndex].selectedItem;
//* If the attribute's item's id is the same as the seelected input - do nothing
if(attributeInQuestion === itemTargetValue) {
return
}
//* If the attribute's item's id is not the same - change it to the new value
if(attributeInQuestion !== itemTargetValue) {
state[attributeIndex].selectedItem = itemTargetValue;
console.log(state);
return setitemState(state);
}
}
};
Here is the working code that fixes the issue.
Yes, there is some streamlining, for example, code shortening, etc. Yet, the difference that solves the issue is that...
The code that I had posted in the question originally was working. Meaning, that it was firing the inputClick() function and changing which input was selected, the problem was that...
...the defaultChecked logic in the was preventing the chosen input from being rendered as a selected input a.k.a. to change its CSS styling.
Bellow is the new onClick() function.
//* Handle input selection
const inputClick = (product, attribute, event) => {
let newCart = JSON.parse(JSON.stringify(cartState));
const productId = product.id;
const attributeId = attribute.id;
const itemTargetValue = event.target.value;
//* Find the product in cart state */
const productIndex = newCart.map((object) => object.id).indexOf(productId);
//* Find the attribute by id in question */
const attributeIndex = newCart[productIndex].selectedAttributes.map(object => object.id).indexOf(attributeId);
//* Change the products selected attribute item */
newCart[productIndex].selectedAttributes[attributeIndex].selectedItem = itemTargetValue;
setcartState(newCart);
};
Below is what the "inside" of the looks like now.
<input
type='radio'
key={product.id + attribute.name + item.id}
id={product.id + attribute.name + item.id}
name={product.id + attribute.name}
value={item.value}
defaultChecked={product.selectedAttributes[selectedId].selectedItem === item.value}
onChange={(event) => inputClick(product, attribute, event)}
>
</input>

I need to set and send value of slider after onChange

I am using material PrettoSlider I need to set on change properly so if any value gets change I am able to submit that value but what happening right now if I change something means if I click one time I will get value null if I click two times in same value then value get the print I need to set onChnage using formik and need to set field value properly so if I submit then that change value gets submitted whatever value get to change it storing in event.target.ariaValueNow
how can I set Field values properly
export default function CustomizedSlider() {
const classes = useStyles();
const ruleForm = useFormik({
initialValues: {
partialNameMatchThreshold: 40
},
enableReinitialize: true,
onSubmit: (values) => {
alert(JSON.stringify(values, null, 2));
}
});
return (
<div className={classes.root}>
<Typography gutterBottom>pretto.fr</Typography>
<PrettoSlider
onChange={(event) => {
console.log("Number change ", event.target.ariaValueNow);
ruleForm.setFieldValue(event.target.ariaValueNow);
}}
valueLabelDisplay="on"
aria-label="pretto slider"
defaultValue={ruleForm.values.partialNameMatchThreshold}
marks={marks}
name="partialNameMatchThreshold"
/>
<Button
onSubmit={ruleForm.handleSubmit}
variant="contained"
color="primary"
type="submit"
>
Commit Changes
</Button>
</div>
);
}
CodeSandBox Link
We should not be using the event to capture the selected value . There is a second argument provided by the onChange method which holds the actual selected value.
onChange={(event, newValue) => {
we need to use the newValue instead of event.
Formik's setFieldValue takes 2 arguments , one is the field which you need to update and the other is the value to update .
ruleForm.setFieldValue("partialNameMatchThreshold", newValue);
Slider component needs to read the value from the Formik to keep the value in sync . So we need to make the slider as a controlled component . Add this new value prop to the slider
value={ruleForm.values.partialNameMatchThreshold}
Codesandbox

Work out whether custom radio component is checked or not

I have a custom radio component in React, when I check and uncheck the values it adds items to an object and should have true or false based on whether they are checked.
At the moment it adds the true value correctly with the name of the radio but I can't seem to find out how to work to make the option false if another option is chosen.
I am currently using
constructor() {
super();
this.state = {
time_frame: {},
}
this.handleRadioChange = this.handleRadioChange.bind(this);
}
handleRadioChange(event) {
let name = event.target.name
let timeFrameCopy = this.state.time_frame;
console.log(event.target)
timeFrameCopy[event.target.value] = true
this.setState({[name]: timeFrameCopy,}, this.checkState)
return
}
}
checkState(event) {
console.log(this.state)
}
My radio component is
const Radio = (props) => {
return (
<Col>
<div>
<input id={props.value} type="radio" name={props.name} value={props.value} className="visually-hidden" onChange={props.handleChange}/>
<label htmlFor={props.value} className="switch-label checkbox-label text-center">{props.label}</label>
</div>
</Col>
)
}
export default Radio
If I check one radio button and then the other my state still has the data:
time_frame: {single: true, recurring: true}
Even though I would expect one of them to be false
If I understand correctly, you're trying to store in the state an object called time_frame, which is going to contain one pair of property-value per radio input, where the name of each of them would be the property name and the checked status the value. If that's the case, I see a logic problem. since you're hard-coding true (for what I understand from your code) always instead of looking for the value stored and toggling/flipping it.
handleRadioChange() function should be something like:
handleRadioChange(event) {
let name = event.target.name;
this.setState((currentState)=>{
let timeFrameCopy = currentState.time_frame;
timeFrameCopy[name] = event.target.checked;
return { "time_frame": timeFrameCopy };
});
}

How to access/reference component values inside a component

Trying to build a react component where I need to control checked status of checboxes and select options when change event occurs. But I don't know how it is possible to get value of the checked checkbox(es) and set the state.
We're using custom data-binding. On page load, we're assigning selected value of the select, with jQuery.
Programmatically changing value of the select must update matching check-boxes.
When user checks/unchecks a checkbox, corresponding value must be toggled on the select.
With jQuery I would loop trough check-boxes and build array with checked values then assign this value to the select on checkbox change. And when select change event is triggered, I would uncheck all check-boxes and check the ones matching selected items.
This is my simplified code.
state = {
items: [
{Key: 1, Value: "A"},
{Key: 29, Value: "Z"}
],
selected: [1, 29]
}
function onSelectChange(){
// Update checked checkboxes
}
function onCheckboxChange(){
// Update selected options
}
<div>
<select multiple onChange={onSelectChange} className="hidden">
{this.state.items.map((item, i) =>
<option value={item.Key}>{item.Value}</option>
)}
</select>
<div className="checkboxes">
{this.state.items.map((item, i) =>
<input
type="checkbox"
key={i}
checked={this.state.selected.indexOf(item.Key) >= 0}
onChange={onCheckboxChange} />
)}
</div>
</div>
You would use this.setState({}) inside the event handler to update the state of a component in React. This triggers a rerender in React which allows you to query the the updated state (this.state.selected).
Be advised that this.setState() expects an immutable object, so you should never change the previous, but always set a new state object!
Answer to comment:
For selectItem:
onSelectChange = event => this.setState({selected:event.target.value})
and for checkboxes (note the prevState):
onCheckboxChange = item => event => this.setState(({selected,...prevState})=> ({
...prevState,
selected: event.target.checked? selected.concat(item): selected.filter(it=> it!== item)
}))
and usage:
{this.state.items.map((item, i) =>
<input
type="checkbox"
key={i}
checked={this.state.selected.indexOf(item.Key) >= 0}
onChange={onCheckboxChange(item)} />
)}
This has the downside that it will create a new function on each rerender, so it's better to create a custom CheckboxItem and pass the item to it and use a handleClick.
onChange function give event where you could check whether the select box is being checked or not using this you can update your state accordingly.
function onCheckboxChange(e){
console.log("checked", e.target.checked);
// Then, on the basis of boolean you can update your state
}

Categories