Print only clicked radio button value(React) - javascript

Print selected radio button value in console.
If all radiogroup is answered then print in console only the selected= true radioValue. for example: if NO radiobutton= true its value is 2. It should print value 2. Like that all true radiovalue should print in console.
Thanks
//array of cards coming from the backend
const data = [
{
cardName: 'Do you want sugar in your coffee',
options: [
{ radioName: 'Yes',radioValue: '1', selected: false },
{ radioName: 'No',radioValue: '2', selected: false }]
},
{
cardName: 'Do you want milk in your coffee',
options: [
{ radioName: 'Yes',radioValue: '1', selected: false },
{ radioName: 'No',radioValue: '2', selected: false }]
},
{
cardName: 'Do you want low-fat-milk in your coffee',
options: [
{ radioName: 'Yes',radioValue: '1', selected: false },
{ radioName: 'No',radioValue: '2', selected: false }]
}
];
class CardsList extends React.Component {
constructor(props) {
super(props);
this.state = {
cards: [],
};
}
componentDidMount() {
setTimeout(() => {
// mimic an async server call
this.setState({ cards: data });
}, 1000);
}
onInputChange = ({ target }) => {
const { cards } = this.state;
const nexState = cards.map(card => {
if (card.cardName !== target.name) return card;
return {
...card,
options: card.options.map(opt => {
const checked = opt.radioName === target.value;
return {
...opt,
selected: checked
}
})
}
});
this.setState({ cards: nexState })
}
onSubmit = () => {
console.log(this.state.cards.map(({ cardName, options }) => {
const option = options.filter(({ selected }) => selected)[0]
return ` ${option.radioValue}`
}))
};
onReset = () => {
this.setState({cards:[]});
}
render() {
const { cards } = this.state;
return (
<div>
{
cards.length < 1 ? "Loading..." :
<div>
{cards.map((card, idx) => (
<ul>
{card.cardName}
{card.options.radioName}
{
card.options.map((lo, idx) => {
return <input
key={idx}
type="radio"
name={card.cardName}
value={lo.radioName}
checked={!!lo.selected}
onChange={this.onInputChange}
/>
})
}
</ul>
))
}
< button onClick={this.onSubmit}>Submit</button>
< button onClick={this.onReset}>Clear</button>
</div>
}
</div>
);
}
}
ReactDOM.render(<CardsList />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Change your log in onSubmit to this
console.log(this.state.cards.map(({ cardName, options }) => {
const option = options.filter(({ selected }) => selected)[0]
return `${cardName}: ${option.radioName}`
}))
This way you filter the options to the one, where selected is truthy, and take the first one.
To address your first question, just map over your this.state.cards array before doing the log and check, if there is exactly 1 option, where selected is true. If this is not the case, tell the user in whatever way you want.
Also you can remove your constructor and change it to that:
state = {
cards: [],
}
Because you do not access your props in your constructor

You can go with the answer of #george,
for you to check if either of the radio buttons is clicked for each card, you can run a validation check
let unselectedCards = this.state.cards.filter((card) => {
return !card.options[0].selected && !card.options[1].selected
});
use the unselectedCards variable to highlight the cards.
you can use map options again inside the cards map if you would be having more options.

Related

How to checked multiple checkbox in react.js?

I am using react antd . I have got array of objects that's groupKey .I am mapping checkbox by using Groupkey and also I have got two different types of checkbox . One is Select All Checkbox . it actually works when user click on the Select All or User select on all individual checkbox . Other is individual checkbox , user can Select on individually . when user submit on Button , then it's give me this data format ["manage_books","manage_journals","manage_deals"]
here is my trying code :
let defaultCheckedList = ["manage_deals"];
state = {
groupKey: [{
id: 1,
key: "manage_books",
label: "books"
},
{
id: 2,
key: "manage_journals",
label: "journals"
},
{
id: 3,
key: "manage_deals",
label: "deals"
}
],
checkedList: defaultCheckedList,
output: [],
indeterminate: true,
checkAll: false
};
onCheckAllChange = e => {
this.setState({
checkedList: e.target.checked ?
this.state.groupKey.map(item => item.key) :
[],
indeterminate: false,
checkAll: e.target.checked
});
};
onChange = (e, value) => {
this.setState({
checked: e.target.checked,
output: this.state.output.concat(value)
});
};
onSubmit = () => {
console.log(this.state.output)
}
render(UI)
<
div >
<
div className = "site-checkbox-all-wrapper" >
Select All <
Checkbox
indeterminate = {
this.state.indeterminate
}
onChange = {
this.onCheckAllChange
}
checked = {
this.state.checkAll
}
/> <
/div>
I am looping checkbox by groupKey.I am passing key using onChange method. {
this.state.groupKey.map(item => ( <
div className = "userpermission-content"
key = {
item.id
} > {
item.label
} <
Checkbox onChange = {
(e, value) => this.onChange(e, item.key)
}
value = {
item.key
}
/>{" "} <
/div>
))
} <
button onClick = {
this.onSubmit
} > submit < /button> <
/div>
);
}
}
In this code, you can see that two individual checkbox is initial select, I need to get completely like this: https://codesandbox.io/s/4k6qi
this is my codesanbox: https://codesandbox.io/s/check-all-ant-design-demo-vhidd?file=/index.js
Here is what I have come up with
https://codesandbox.io/s/check-all-ant-design-demo-6cm2v?file=/index.js
import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Checkbox } from "antd";
const CheckboxGroup = Checkbox.Group;
class App extends React.Component {
state = {
groupKey: [
{ id: 1, key: "manage_books", label: "books" },
{ id: 2, key: "manage_journals", label: "journals" },
{ id: 3, key: "manage_deals", label: "deals" }
],
checked: {},
output: [],
indeterminate: true,
checkAll: false
};
onCheckAllChange = e => {
const { groupKey } = this.state;
const checked = groupKey.reduce((prev, curr) => {
return { ...prev, [curr.key]: e.target.checked };
}, {});
this.setState({ checked, checkAll: e.target.checked });
};
checkAll = () => {};
onChange = (e, value) => {
// this.setState({
// checked: e.target.checked,
// output: this.state.output.concat(value)
// });
this.setState(
state => ({
checked: { ...state.checked, [value]: e.target.checked }
}),
() => {
const { checked, groupKey } = this.state;
const values = Object.values(checked);
if (values.length === groupKey.length && values.every(v => v)) {
this.setState({ checkAll: true });
} else {
this.setState({ checkAll: false });
}
}
);
};
render() {
console.log(this.state.output);
const { checked, checkAll } = this.state;
return (
<div>
<div className="site-checkbox-all-wrapper">
Select All
<Checkbox
// indeterminate={this.state.indeterminate}
onChange={this.onCheckAllChange}
checked={checkAll}
/>
</div>
{this.state.groupKey.map(item => (
<div className="userpermission-content" key={item.id}>
{item.label}
<Checkbox
onChange={e => this.onChange(e, item.key)}
value={item.key}
checked={checked[item.key]}
/>{" "}
</div>
))}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("container"));

setState array of objects without changing objects order

In state, I have an array of list objects and would like to toggle the displayAddTaskForm. Every time I set state, the list that gets clicked gets rearranged and moves to the front of the lists on the UI. I believe I know why this is happening, just not sure of the solution. When I setState in toggleAddTaskForm, toggledList is first and then the other lists. How do I update the toggledList without changing the order of the lists. Here is the code.
this.state = {
lists: [
{
id: 1,
header: "To Do",
displayAddTaskForm: false,
},
{
id: 2,
header: "Working on It",
displayAddTaskForm: false,
},
{
id: 3,
header: "Taken Care Of",
displayAddTaskForm: false,
}
],
toggleAddTaskForm: (list) => {
const toggledList = {...list, displayAddTaskForm: !list.displayAddTaskForm}
const otherLists = this.state.lists.filter(l => l.id !== list.id)
this.setState({
lists: [toggledList, ...otherLists]
})
},
}
Putting function in the state is not a common thing. I think you need to seperate that function from state.
You can easily toggle items using Array.map() and checking the clicked item id with the item id. This will not change the order of items.
You can use the following code to toggle only one item:
class App extends Component {
constructor() {
super();
this.state = {
lists: [
{
id: 1,
header: "To Do",
displayAddTaskForm: false
},
{
id: 2,
header: "Working on It",
displayAddTaskForm: false
},
{
id: 3,
header: "Taken Care Of",
displayAddTaskForm: false
}
]
};
}
handleClick = id => {
let newList = this.state.lists.map(item => {
if (item.id === id) {
return {
...item,
displayAddTaskForm: !item.displayAddTaskForm
};
} else {
return {
...item,
displayAddTaskForm: false
};
}
});
this.setState({ lists: newList });
};
render() {
return (
<div>
<ul>
{this.state.lists.map(({ id, header, displayAddTaskForm }) => {
return (
<li key={id} onClick={() => this.handleClick(id)}>
{header} - Toggle Value: {displayAddTaskForm ? "true" : "false"}
</li>
);
})}
</ul>
</div>
);
}
}
Playground
Or if you want to be able to toggle every item, you can change the handleClick function like this:
handleClick = id => {
let newList = this.state.lists.map(item => {
if (item.id === id) {
return {
...item,
displayAddTaskForm: !item.displayAddTaskForm
};
} else {
return {
...item
};
}
});
this.setState({ lists: newList });
};
Playground
You could find the index of the list, copy the lists, and insert the modified list into the new lists array at the same index.
toggleAddTaskForm: (list) => {
const toggledList = {...list, displayAddTaskForm: !list.displayAddTaskForm}
const newLists = [...this.state.lists];
newLists[this.state.lists.indexOf(list)] = toggledList;
this.setState({
lists: newLists
})
}
This might help.
lists = [{
id: 1,
header: "To Do",
displayAddTaskForm: false,
}, {
id: 2,
header: "Working on It",
displayAddTaskForm: false,
}, {
id: 3,
header: "Taken Care Of",
displayAddTaskForm: false,
}]
const toggle = (list)=>{
const toggledList = {
...list,
displayAddTaskForm: true
}
const indexOfList = lists.findIndex(({id}) => id === list.id)
const newLists = [...lists]
newLists[indexOfList] = toggledList
setState({
lists: newLists
})
}
const setState = (o) => console.log(o)
toggle(lists[1])

Adding clicked items to new array in React

I am making API calls and rendering different components within an object. One of those is illustrated below:
class Bases extends Component {
constructor() {
super();
this.state = {
'basesObject': {}
}
}
componentDidMount() {
this.getBases();
}
getBases() {
fetch('http://localhost:4000/cupcakes/bases')
.then(results => results.json())
.then(results => this.setState({'basesObject': results}))
}
render() {
let {basesObject} = this.state;
let {bases} = basesObject;
console.log(bases);
//FALSY values: undefined, null, NaN, 0, false, ""
return (
<div>
{bases && bases.map(item =>
<button key={item.key} className="boxes">
{/* <p>{item.key}</p> */}
<p>{item.name}</p>
<p>${item.price}.00</p>
{/* <p>{item.ingredients}</p> */}
</button>
)}
</div>
)
}
}
The above renders a set of buttons. All my components look basically the same.
I render my components here:
class App extends Component {
state = {
ordersArray: []
}
render() {
return (
<div>
<h1>Bases</h1>
<Bases />
<h1>Frostings</h1>
<Frostings />
<h1>Toppings</h1>
<Toppings />
</div>
);
}
}
I need to figure out the simplest way to, when a button is clicked by the user, add the key of each clicked element to a new array and I am not sure where to start. The user must select one of each, but is allowed to select as many toppings as they want.
Try this
We can use the same component for all categories. All the data is handled by the parent (stateless component).
function Buttons({ list, handleClick }) {
return (
<div>
{list.map(({ key, name, price, isSelected }) => (
<button
className={isSelected ? "active" : ""}
key={key}
onClick={() => handleClick(key)}
>
<span>{name}</span>
<span>${price}</span>
</button>
))}
</div>
);
}
Fetch data in App component, pass the data and handleClick method into Buttons.
class App extends Component {
state = {
basesArray: [],
toppingsArray: []
};
componentDidMount() {
// Get bases and toppings list, and add isSelected attribute with default value false
this.setState({
basesArray: [
{ key: "bases1", name: "bases1", price: 1, isSelected: false },
{ key: "bases2", name: "bases2", price: 2, isSelected: false },
{ key: "bases3", name: "bases3", price: 3, isSelected: false }
],
toppingsArray: [
{ key: "topping1", name: "topping1", price: 1, isSelected: false },
{ key: "topping2", name: "topping2", price: 2, isSelected: false },
{ key: "topping3", name: "topping3", price: 3, isSelected: false }
]
});
}
// for single selected category
handleSingleSelected = type => key => {
this.setState(state => ({
[type]: state[type].map(item => ({
...item,
isSelected: item.key === key
}))
}));
};
// for multiple selected category
handleMultiSelected = type => key => {
this.setState(state => ({
[type]: state[type].map(item => {
if (item.key === key) {
return {
...item,
isSelected: !item.isSelected
};
}
return item;
})
}));
};
// get final selected item
handleSubmit = () => {
const { basesArray, toppingsArray } = this.state;
const selectedBases = basesArray.filter(({ isSelected }) => isSelected);
const selectedToppings = toppingsArray.filter(({ isSelected }) => isSelected);
// submit the result here
}
render() {
const { basesArray, toppingsArray } = this.state;
return (
<div>
<h1>Bases</h1>
<Buttons
list={basesArray}
handleClick={this.handleSingleSelected("basesArray")}
/>
<h1>Toppings</h1>
<Buttons
list={toppingsArray}
handleClick={this.handleMultiSelected("toppingsArray")}
/>
</div>
);
}
}
export default App;
CSS
button {
margin: 5px;
}
button.active {
background: lightblue;
}
I think the following example would be a good start for your case.
Define a handleClick function where you can set state with setState as the following:
handleClick(item) {
this.setState(prevState => {
return {
...prevState,
clickedItems: [...prevState.clickedItems, item.key]
};
});
}
Create an array called clickedItems in constructor for state and bind handleClick:
constructor() {
super();
this.state = {
basesObject: {},
clickedItems: [],
}
this.handleClick = this.handleClick.bind(this);
}
You need to add a onClick={() => handleClick(item)} handler for onClick:
<button key={item.key} className="boxes" onClick={() => handleClick(item)}>
{/* <p>{item.key}</p> */}
<p>{item.name}</p>
<p>${item.price}.00</p>
{/* <p>{item.ingredients}</p> */}
</button>
I hope that helps!

Change the state of an array of checkboxes on the reducer as it changes in the UI

I have something like this on React:
const CheckboxItems = (t) => [ // that t is just a global prop
{
checked: true,
value: 'itemsCancelled',
id: 'checkBoxItemsCancelled',
labelText: t('cancellations.checkBoxItemsCancelled'),
},
{
checked: true,
value: 'requestDate',
id: 'checkboxRequestDate',
labelText: t('cancellations.checkboxRequestDate'),
},
{
checked: true,
value: 'status',
id: 'checkboxStatus',
labelText: t('cancellations.checkboxStatus'),
},
{
checked: true,
value: 'requestedBy',
id: 'checkboxRequestedBy',
labelText: t('cancellations.checkboxRequestedBy'),
},
];
class TableToolbarComp extends React.Component {
state = {
items: CheckboxItems(),
};
onChange = (value, id, event) => {
const { columnsFilterHandler } = this.props;
this.setState(({ items }) => {
const item = items.slice().find(i => i.id === id);
if (item) {
item.checked = !item.checked;
columnsFilterHandler(id, item.value, item.checked);
return { items };
}
});
};
render() {
const { items } = this.state;
return(
<>
{items.map(item => (
<ToolbarOption key={item.id}>
<Checkbox
id={item.id}
labelText={item.labelText}
value={item.value}
checked={item.checked}
onChange={this.onChange}
/>
</ToolbarOption>
))}
</>
)
}
export default compose(
connect(
({ cancellations }) => ({
columnId: cancellations.columnId,
columnValue: cancellations.columnValue,
isChecked: cancellations.isChecked,
}),
dispatch => ({
columnsFilterHandler: (columnId, columnValue, isChecked) => {
dispatch(columnsFilterAction(columnId, columnValue, isChecked));
},
}),
),
)(translate()(TableToolbarComp));
That works very well and it is dispatching the data I would need to use later.
But I have a mess on the Redux part which is changing the state of all of the checkboxes at once and not separately as it should. So, once I uncheck one of the checkboxes the other 3 also get checked: false. I don't see this change to checked: false on the UI, only I see it on the Redux console in the browser.
This is what I have in the reducer
const initialState = {
checkboxes: [
{
checked: true,
value: 'itemsCancelled',
id: 'checkBoxItemsCancelled',
},
{
checked: true,
value: 'requestDate',
id: 'checkboxRequestDate',
},
{
checked: true,
value: 'status',
id: 'checkboxStatus',
},
{
checked: true,
value: 'requestedBy',
id: 'checkboxRequestedBy',
},
],
}
[ActionTypes.COLUMNS_FILTER](state, action) {
return initialState.checkboxes.map(checkbox => {
if (!checkbox.id === action.payload.id) {
return checkbox;
}
return {
...checkbox,
checked: action.payload.isChecked,
};
});
}
Action:
const columnsFilterAction = (columnId, columnValue, isChecked) => ({
type: ActionTypes.COLUMNS_FILTER,
payload: { columnId, columnValue, isChecked },
});
So all I need to know is what I have to do manage the state of those checkboxes on Redux as it working on React. As all I see is that when I toggle the checkboxes all of them reach the same state.
You have !checkbox.id === action.payload.id as your condition logic. As all of your checkbox IDs are 'truthy', then this !checkbox.id evaluates to false, and is the same as writing if(false === action.payload.id).
I suspect you meant to write: if(checkbox.id !== action.payload.id).
What you want to do is pass the id of the checkbox you want to toggle in an action. That's all you need in an action to toggle state. Then in the reducer you want to map over the current state and just return the checkbox for any that don't match the id passed in the action. When the id does match, return a new option spreading the current checkbox's properties into the new object and setting the checked property to it's opposite.
Given this action:
const TOGGLE_CHECKBOX = 'TOGGLE_CHECKBOX'
function toggleCheckbox(id) {
return {
type: TOGGLE_CHECKBOX,
id
}
}
Actions - Redux - Guide to actions and action creators provided by the author of Redux.
This reducer will do the job.
function checkboxReducer(state = [], action = {}) {
switch(action.type) {
case TOGGLE_CHECKBOX:
return state.map(checkbox => {
if (checkbox.id !== action.id) {
return checkbox;
}
return {
...checkbox,
checked: checkbox.isChecked ? false : true,
}
})
default:
return state;
}
}
Reducers - Redux - Guide to reducers and how to handle actions provided by the author of Redux.
Here is a working Code Sandbox to demonstrate it working. You can click the checkboxes to see them toggling as expected.

Remove from array if unchecked with React

When checked, add to array. When unchecked, remove from array. My code below works but null is placed in its place. I need to remove it completely. How?
...
getInitialState: function(){
return{
email: this.props.user,
product: []
}
},
_product: function(){
if (this.refs.opt1.checked) {
var opt1 = this.refs.opt1.value;
} else {
this.setState({ product: this.state.product.filter(function(_, i) { return i }) });
};
if (this.refs.opt2.checked) {
var opt1 = this.refs.opt2.value;
} else {
this.setState({ product: this.state.product.filter(function(_, i) { return i }) });
};
var array = this.state.product.concat([opt1]);
this.setState({
product: array
});
},
render: function(){
return(
<div><input ref="opt1" type="checkbox" value="foo" onClick={this._product}/></div>
)
}
...
I think it would be easier to manage if you kept an array of options, where each option has a selected property. Something along the lines of:
...
constructor(props) {
super(props);
this.toggleOption = this.toggleOption.bind(this);
}
getInitialState(){
return {
email: this.props.user,
options: [
{ value: 'Foo1', otherProperty: 'something', checked: false },
{ value: 'Foo2', otherProperty: 'something', checked: false },
],
}
}
toggleOption(index) {
// Clone the options array
const options = this.state.options.slice();
// Toggle the option checked property
if(options[index]) {
options[index].checked = !options[index].checked;
}
// Update the component state
this.setState({
options
});
}
getSelectedOptions() {
// Use this to grab an array of selected options for whatever reason...
return this.state.options.filter(option => option.checked);
}
render: function(){
return(
<div>
{ this.state.options.map((i, option) => {
<input type="checkbox" checked={option.checked} value={option.value} onClick={() => this.toggleOption(i) } />
}) }
</div>
)
}
...

Categories

Resources