REACT.js initial radio select - reactjs

I have been trying to modify existing code by adding a few of new functionalities.
I have this function that renders set of radiobuttons based on variable ACCREDITATION_TYPES:
createRadioCalibration(name) {
const { id, value, labels } = this.props;
const _t = this.props.intl.formatMessage;
const ACCREDITATION_TYPES = [
[CALIBRATION_ACCREDITED, _t(messages.calibrationAccredited)],
[CALIBRATION_NOT_ACCREDITED, _t(messages.calibrationNotAccredited)]
];
return <FormChoiceGroup
type = "radio"
values = {ACCREDITATION_TYPES.map(mapValueArray)}
key = {`${id}_${name}`}
name = {`${id}_${name}`}
value = {value[name]}
handleChange = {this.handleFieldChangeFn(name)}
/>;
}
The radios by default are all unchecked. When clicked this function is fired up:
handleFieldChangeFn(name) {
return (e) => {
const { handleFieldChange, id } = this.props;
handleFieldChange(id, name, e.target.value);
};
}
The form is rendered as follows:
render () {
const FIELDS = {
[CALIBRATION]: this.createRadioCalibration(CALIBRATION),
};
return (
<div className="">
<label>{_t(messages.calibration)}</label>
{ FIELDS[CALIBRATION] }
How can I select any option I want as an initial state? There are only two options now but what if there were five?
Also how can I manipulate the radio selection based on onChange event of other elements of the form, namely a drop down menu?

Answering my question I got two minuses for asking: in the constructor one needs to add the following this.props.handleFieldChange( 'id', 'radio_button_group_name', 'value_of_the_output_that_should_be_selected' );
That will select particular radio in a loop.

Related

Filter Checkbox issue in react js

This is my code for the category filter. I used this in all places.
{categapi.map((data, index) => (
<Form.Check
onChange={props.handleSingleCheck }
key={index}
name={data.category_id}
label={data.category_name}
type="checkbox"
id={data.category_name}
/>
))}
It's the function for the handle the checkbox.
const handleSingleCheck = (e) => {
if (e.target.checked == true) {
const { name } = e.target;
isChecked.push(name);
console.log(isChecked);
setIsChecked([...isChecked]);
} else {
let index = isChecked.indexOf(e.target.name);
isChecked.splice(index, 1);
}
catfilter();
};
when selecting two categories it is selected. But when I click the more button it opens the modal but the selected items are disabled in the modal.
When clicking on the checkbox it needs to check both inside the modal and outside the modal. How to do this?
In your handleSingleCheck function you are pushing the values and slicing the state variable isChecked directly. Which is the wrong way to interact with react state. Learn more here (you should treat the state variables as if they were immutable)
Change your handleSingleCheck logic as follows:
const handleSingleCheck = (e) => {
let isCheckedCopy = [...isChecked] // create a local variable
if (e.target.checked == true) {
const { name } = e.target;
isCheckedCopy.push(name) // push the data into local mutable array
} else {
let index = isCheckedCopy.indexOf(e.target.name);
isCheckedCopy.splice(index, 1); // slice the mutable array
}
console.log(isCheckedCopy);
setIsChecked([...isCheckedCopy]); // change isChecked state through setIsChecked(...)
catfilter();
};

Getting an Empty array in props

I am trying to make table using react-table in which one of the columns will be a toggle-switch in typescript. I am using the following code to create a react-switch.
const tableInstance = useTable({
columns,
data},(hooks)=> {
console.log("setting buildings: ",data);
hooks.visibleColumns.push((columns) => columns.map((column)=>column.id === "cevacrunningstatus"?{...column,Cell:({row})=>
{return <BuildingStartStopSwitch row_={row} data__={buildings} setdata={setbuildings}/>}}:column));
}
)
I am using the following React function component
interface props{
row_:Row.Row<any>;
data__:BuildingControlStatus[];
setdata: React.Dispatch<React.SetStateAction<BuildingControlStatus[]>>;
}
const BuildingStartStopSwitch:React.FC<props> = ({row_,data__,setdata}) => {
const [state,setState] = useState<boolean>(row_.values.runningstatus);
const handleChange = (checked:boolean) => {
setState(checked);
console.log("Data before statechange: ",data__)
setdata(data__.map((data_)=>row_.values.ccid === data_.ccid?({...data_,runningstatus:checked}):data_))
}
console.log("Data after statechange: ",data__)
return (
<Switch onChange={handleChange} checked={state}/>
);
};
export default BuildingStartStopSwitch;
I have the following issue:
The array data__ is turning up as an empty array inside BuildingStartStopSwitch. The data variable which is assigned to data__ contains items, but the same is not reflected inside BuildingStartStopSwitch. I am trying to update the data variable(which is the table data) to reflect the status of toggle switch.
I have an input cell against each toggle switch in a row. When the switch is checked, the input should be enabled and when the switch is unchecked , it should be disabled. I am not sure how to implement.
Thanks in advance!

React Redux how to retrieve object from state array based on button click

I'm working on a project where a user can input multiple exercise names/weights. These go into a state array as objects. For example:
[
{
name: bench
weight: 100
},
{
name: squat:
weight: 200
}
]
Each of these objects becomes a button that displays the name and weight. What I want to happen is allow the user to click the button and navigate to another page where that specific name and weight are displayed, but I can't figure out how to do that. Currently, I am getting the whole state array instead of just the specific one clicked.
Here is my button component:
const MovementButtons = (props) => {
const navigate = useNavigate();
const {
move
} = props;
const mapMoves = move.map((movement) => {
return (
<Button
key={movement.name}
onClick={() => navigate(`/movement/${movement.name}/${movement.weight}`)}
>
{movement.name} - {movement.weight}
</Button>
)
})
return <div>{mapMoves}</div>
};
const mapStateToProps = state => {
return {
move: state.moveReducer
}
};
export default connect(mapStateToProps)(MovementButtons);
Here is the page where the button redirects to and where I want to try and get the name of the button that was clicked:
const PercentChart = (props) => {
const {
move
} = props;
return (
<div>
{move.name}
{move.weight}
</div>
);
};
const mapStateToProps = (state) => {
return {
move: state.moveReducer,
}
};
export default connect(mapStateToProps)(PercentChart);
So right now if I click on the button labeled "bench" for example, I get redirected to the PercentChart page, where instead of getting just the "bench" object I get the whole state array. Can anyone point me in the right direction on how I can get the specific object based on the button that was clicked? If I am missing code that needs to be shown let me know and I'll update.

How to update a Textfield that has a value from an array of objects state variable in React?

In react I am trying to update a rendered mapped array of objects in Textfields with the value set to the objects value and then also be able to update/change the value in the Textfield and corresponding state value. Currently the array of objects is correctly being mapped and displayed with the objects value, however when trying to change the value within the TextField, nothing changes in the display and the console logs result in only changing the last letter of the value. It seems as though because I need the Textfield to start with a value, that value keeps the old value due to the data being rendered with a map or whether I am updating an array of objects wrong? Although in this example an array of objects is not needed, it applies to my component that does need it.
The following is some example code to demonstrate:
import React, { useState} from 'react';
const Test = () => {
const [data, setData] = useState([
{
num: 1,
name: 'hello'
},
{
num: 2,
name: 'world'
},
{
num: 3,
name: 'test'
},
]);
const handleChange = e => {
const { name, value, id } = e.target;
setData(data[id].name = value)
console.log(value)
}
return (
<div>
{
data.map((_itm, index) => (
<TextField key={index} value={_itm.name} onChange={handleChange} name='name' id={index.toString()}/>
))
}
</div>
)
}
So 3 textfields will be displayed with the values, hello, world, and test. When trying to edit the textfields, the values do not change.
Any and all help is appreciated, thank you.
In the state hook, data is set to be an array. So you should always pass in an updated copy of that array whenever calling setData.
const handleChange = e => {
const { value, id } = e.target;
// Make a shallow copy of the current `data`.
const newArray = [...data];
// Update the changed item.
newArray[id] = {
...newArray[id],
name: value
}
// Call setData to update.
setData(newArray);
console.log(value);
}
I had the same problem and the code above didn't work. I did it a little differently and wrote a code that works 100%, no matter how you name the key in the object
const changeHandler = (e) => {
const { id, name, value } = e.target
const newArray = [...data]
newArray[id][name] = value
setForm(newArray)
}

How to create a questionnaire type form using Ant Design?

Ant Design provides a Dynamic Form Item, by using that, I can add and remove multiple fields. But now I want do nesting in that, i.e., I want to create a questionnaire like form in which I want to add multiple questions and their respective answers.
Currently, when I am adding questions, its working correct but when I am adding answer to one question, its also adding to the all questions.
The functions of adding and removing questions and answers are as given below:
remove = k => {
const { form } = this.props;
// can use data-binding to get
const keys = form.getFieldValue("keys");
// We need at least one passenger
if (keys.length === 1) {
return;
}
// can use data-binding to set
form.setFieldsValue({
keys: keys.filter(key => key !== k)
});
};
add = () => {
const { form } = this.props;
// can use data-binding to get
const keys = form.getFieldValue("keys");
const nextKeys = keys.concat(uuid);
uuid++;
// can use data-binding to set
// important! notify form to detect changes
form.setFieldsValue({
keys: nextKeys
});
};
remove1 = k1 => {
const { form } = this.props;
// can use data-binding to get
const keys1 = form.getFieldValue("keys1");
// We need at least one passenger
if (keys1.length === 1) {
return;
}
// can use data-binding to set
form.setFieldsValue({
keys: keys1.filter(key1 => key1 !== k1)
});
};
add1 = () => {
const { form } = this.props;
// can use data-binding to get
const keys1 = form.getFieldValue("keys1");
const nextKeys1 = keys1.concat(uuid1);
uuid1++;
// can use data-binding to set
// important! notify form to detect changes
form.setFieldsValue({
keys1: nextKeys1
});
};
I have created a demo on codesandbox.io.
The problem is not in the functions but in getFieldDecorator:
<FormItem>
{getFieldDecorator(`answer[${k}]`, {
validate: [
...
]
})(<Input type="" placeholder=" Enter Answer" />)
You submit the same input value for all inputs.
Without the decorator it works fine and you can put validation to your custom function and call it
<FormItem>
<Input
type=""
placeholder=" Enter Answer"
// value={this.state.answer}
// onChange={e => this.handleChange(e)}
/>
</FormItem>
UPD: Added the full code - Sandbox try

Resources