Checkbox does not want to check or uncheck after clicking - javascript

Iterates on the todos array. Objects inside have the isChecked property. If isChecked === true marks the checkbox, ifisChecked === false the checkbox is uncheckbox. When I click on the checkbox. I can't mark or uncheckbox
Demo here: https://stackblitz.com/edit/react-ds9rsd
class App extends Component {
constructor() {
super();
this.state = {
todos: [
{
name:'A',
id: 1,
isChecked: true
},
{
name:'B',
id: 2,
isChecked: false
},
{
name:'C',
id: 3,
isChecked: true
}
]
};
}
checked = (e) => {
console.log(e.target.checked)
}
render() {
return (
<div>
{this.state.todos.map((todo, index) => {
return <input type="checkbox" checked={todo.isChecked} onChange={(e) => this.checked(e)}/>
})}
</div>
);
}
}

In checked() function you are just logging the value. Instead of that you need to do setState() to save new state.

A possibile solution could be updating the render function like this:
render() {
return (
<div>
{this.state.todos.map((todo, index) => {
return <input label={todo.name} type="checkbox" checked={todo.isChecked}
onChange={(e) => this.checked(todo)}/>
})}
</div>
);
}
and the checked method like this:
checked = (e) => {
this.setState(state => {
const list = state.todos.map((item) => {
if (item.name === e.name) {
return item.isChecked = !item.isChecked;
} else {
return item;
}
});
return {
list,
};
});
}

You will need to add a function and call it for each checkbox
import React, { Component } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import "./style.css";
class App extends Component {
constructor() {
super();
this.state = {
todos: [
{
name: "A",
id: 1,
isChecked: true
},
{
name: "B",
id: 2,
isChecked: false
},
{
name: "C",
id: 3,
isChecked: true
}
]
};
}
checked = index => {
/** get the current state */
let _todos = this.state.todos;
/** assign opposite value: true to false or false to true */
_todos[index].isChecked = !_todos[index].isChecked;
/** update state */
this.setState({ todos: _todos });
};
render() {
return (
<div>
{this.state.todos.map((todo, index) => {
/** call the function passing the index value */
return (
<input
label={todo.name}
type="checkbox"
checked={todo.isChecked}
onChange={this.checked.bind(this, index)}
/>
);
})}
</div>
);
}
}
render(<App />, document.getElementById("root"));

Related

Checkbox doesn't change its value on click in React todo application

Please help me with this I don't understand exactly where I doing wrong. So when I click on the checkbox values are not changing(if it's by default true when I click on the click it should the false). For that in onChange in todoList component I am calling handleClick function there I change the todo.completed value(basically toggling the values).
In App.js inside the handleClick method When do console.log(todo) before returning from the map function value is toggling fine, but it is not updated in the updatedTodo.
App.js
import TodosData from "./todoData";
import TodoList from "./todoList";
import "./styles.css";
class App extends Component {
constructor() {
super();
this.state = {
todos: TodosData
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(id) {
this.setState(prevState => {
const updatedTodo = prevState.todos.map(todo => {
// console.log(updatedTodo);
if(todo.id === id) {
console.log("before the opt "+todo.completed);
todo.completed = !todo.completed
console.log("after the opt "+todo.completed);
}
//console.log(todo);
return todo;
})
console.log(updatedTodo);
return {
todos: updatedTodo
}
});
}
render() {
const todoDataComponents = this.state.todos.map(item => {
return <TodoList key = {item.id} item = {item} handleChange = {this.handleChange} />
})
return (
<div className="todo-list">{todoDataComponents}</div>
);
}
}
export default App;
todoList.jsx
class TodoList extends Component {
constructor(props) {
super(props);
this.state = {}
}
render() {
// console.log(this.props)
return (
<div className="todo-item">
<input
type="checkbox"
checked={this.props.item.completed}
onChange = {() => this.props.handleChange(this.props.item.id)}
/>
<p>{this.props.item.text}</p>
</div>
);
}
}
export default TodoList;
todoData.js
const TodosData = [
{ id: 1, text: "Coding", completed: true },
{ id: 2, text: "Exercise", completed: false },
{ id: 3, text: "Learning", completed: true },
{ id: 4, text: "Programming", completed: true },
{ id: 5, text: "inspire", completed: false },
{ id: 6, text: "motivation", completed: true }
];
export default TodosData;
I can't see any error in your handleChange() method, it should work fine. However, I've just updated some of your code which you can test below.
I changed the name of your TodoList as it's not really a list but an item. I also changed it to a functional component as it's only presentational, there is no need to have its own state. Instead of adding a p tag after the input, you should use a label to make it accessible.
I haven't really changed anything inside your handleChange() method, only removed the console.logs and it works as expected.
Update: You're using React.StrictMode, where React renders everything twice on dev. As your handleChange() runs twice, it sets the clicked todo's completed state twice, making it to set back to its original state. So if it's false on first render it sets to true on click, but it's rendered again and on the second one it's back to false. You won't notice it as it's pretty fast.
To avoid it, you need to avoid mutating anything. So I've updated your onChange handler, it returns a new object if the completed property is changed.
Feel free to run the code snippet below and click on the checkboxes or the item texts.
const TodosData = [
{ id: 1, text: 'Coding', completed: true },
{ id: 2, text: 'Exercise', completed: false },
{ id: 3, text: 'Learning', completed: true },
{ id: 4, text: 'Programming', completed: true },
{ id: 5, text: 'Inspire', completed: false },
{ id: 6, text: 'Motivation', completed: true },
];
function TodoItem(props) {
const { handleChange, item } = props;
return (
<div className="todo-item">
<input
type="checkbox"
id={`item-${item.id}`}
checked={item.completed}
onChange={() => handleChange(item.id)}
/>
<label htmlFor={`item-${item.id}`}>{item.text}</label>
</div>
);
}
class App extends React.Component {
constructor() {
super();
this.state = {
todos: TodosData,
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(id) {
this.setState((prevState) => {
const updatedTodo = prevState.todos.map((todo) => {
return todo.id === id ? {
...todo,
completed: !todo.completed,
} : todo;
});
return {
todos: updatedTodo,
};
});
}
render() {
const { todos } = this.state;
return (
<div className="todo-list">
{todos.map((item) => (
<TodoItem
key={item.id}
item={item}
handleChange={this.handleChange}
/>
))}
</div>
);
}
}
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
body {
font-family: sans-serif;
line-height: 1.6;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Instead of using an additional variable, you can do it in one line. Can u see if this works for you.
handleChange(id) {
this.setState(prevState => prevState.map(todo => todo.id === id ? {...todo, completed: !todo.completed} : todo )
}

Why checkboxes dont change from checked to unchecked on click?

My React App doesn't work like it should be. The problem is that the checkboxes dont change at all.
I managed to show the checked boxes (the ones with the property of completed=true) and debugging it seems that it works fine when I click but for some reason the box that needs to be changed automatically re-changes on its own.
Do you have any idea why ?
//APP.JS
import React from "react"
import './App.css';
import Header from "./Header"
import TodoItem from "./todoItem";
import todosData from "./todosData"
class App extends React.Component {
constructor() {
super()
this.state = {
todos: todosData
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(id) {
this.setState((prevState) => {
const newArray = prevState.todos.map((elem) => {
if(elem.id === id) {
elem.completed = !(elem.completed)
}
return elem
})
return {
todos: newArray
}
})
}
render() {
const todosArray = this.state.todos.map(item =>
<TodoItem
key={item.id}
item={item}
handleChange={this.handleChange}
/>)
return (
<div className="App">
<Header />
<div className="container">
{todosArray}
</div>
</div>
)
}
}
export default App;
//TODOITEM.JS
import React from "react"
function TodoItem(props) {
return (
<div className="elem-container">
<input type="checkbox"
checked={props.item.completed}
onChange={() => props.handleChange(props.item.id)}
/>
<span className="span-container">{props.item.text}</span>
</div>
)
}
export default TodoItem
//TODOSDATA.JS
const todosData = [
{
id: 1,
text: "Take out the trash",
completed: true
},
{
id: 2,
text: "Grocery shopping",
completed: false
},
{
id: 3,
text: "Clean gecko tank",
completed: false
},
{
id: 4,
text: "Mow lawn",
completed: true
},
{
id: 5,
text: "Catch up on Arrested Development",
completed: false
}
]
export default todosData
Thank you for the help in advance
you need to change two things and it will work just fine
first:
inside todoItem.js
onChange={(e) => props.handleChange(e,props.item.id)}
second:
inside the parent file
handleChange(event, id) {
this.setState((prevState) => {
const newArray = prevState.todos.map((elem) => {
if(elem.id === id) {
elem.completed = event.target.checked
}
return elem
})
return {
todos: newArray
}
})
}
now everything will work as you expected
have a nice day
I'm no expert as I'm learning React myself but looking at the code handleChange(id) doesn't have an else state in its 'if' statement, have you tried adding?
Adding to #mouheb answer, you can simplify one more step. you don't need to map the all elements to update single item. you can change directly item (if it is mutable).
// todoItem.js
onChange={(e) => props.handleChange(e, props.item) }
// parent file
handleChange(event, prop) {
prop.completed = event.target.
this.setState({ todos: this.state.todos }) or this.setState({ todos: [...this.state.todos] })
}

Handling Multiple Checkboxes ReactJS?

I have rendered a list of checkboxes and i am trying to setup an onChange which tracks the selected input and turns the value to true. But i keep getting an error message and also warning with needing a unique key even though i am passing the index.
This is the CodeSandbox
Please check this complete Code:-
import React from "react";
import "./styles.css";
class App extends React.Component {
state = {
checkboxes: [
{ name: "Check 1", value: false },
{ name: "Check 2", value: false },
{ name: "Check 3", value: false }
]
};
checkboxStateHandler = (event, idx) => {
const { checkbox } = this.state;
checkbox.checkboxes[idx] = event.target.checked;
this.setState({
checkbox
});
};
renderCheckboxes = () => {
return this.state.checkboxes.map((cb, index) => (
<label>
{cb.name}
<input
type="checkbox"
key={index}
checked={cb.value}
onChange={this.checkboxStateHandler}
/>
</label>
));
};
render() {
return <div>{this.renderCheckboxes()}</div>;
}
}
export default App;
Any help will be appreciated. Thank you :)
This will work for you:
import React from "react";
import "./styles.css";
class App extends React.Component {
state = {
checkboxes: [
{ name: "Check 1", value: false },
{ name: "Check 2", value: false },
{ name: "Check 3", value: false }
]
};
checkboxStateHandler = (event, idx) => {
const { checkboxes } = this.state;
checkboxes[idx] = {
...checkboxes[idx],
value: event.target.checked,
}
this.setState({
checkboxes
});
};
renderCheckboxes = () => {
return this.state.checkboxes.map((cb, index) => (
<label>
{cb.name}
<input
type="checkbox"
key={index}
checked={cb.value}
onChange={e => this.checkboxStateHandler(e, index)}
/>
</label>
));
};
render() {
return <div>{this.renderCheckboxes()}</div>;
}
}
export default App;
You must send the event and index to the method in order to change the value, also checkboxStateHandler needs a little changes.
There are few changes needs to be done under map method,
-> Assign key to the immediate parent under map method and in your case it is label
<label key={index}>
....
</label>
-> Then you have to modify the onChange value like,
<input
type="checkbox"
checked={cb.value}
onChange={(e) => this.checkboxStateHandler(e,index)}
/>
Here the event and index needs to passed down as an arguments.
-> Then in checkboxStateHandler function get the parameters and assign the event.target.checked value to checkboxes[idx].value
checkboxStateHandler = (event, idx) => {
const { checkboxes } = this.state;
checkboxes[idx].value = event.target.checked;
this.setState({
checkboxes
});
};
The above code will get rid of all warnings and errors.
Forked codesandbox here..

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"));

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!

Categories

Resources