clicking checkbox doesn't change it - html

I tried to use handleChange method to change the completed boolean who is responsible for checking the box but it does not change .. I can't find where it's missed up
class App extends React.Component {
constructor() {
super()
this.state = {
todos: todosData
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(id) {
this.setState((prevState) => {
const updatedTodos = prevState.todos.map(todo => {
if (todo.id === id) {
todo.completed = !todo.completed
}
return todo
})
return {
todos: updatedTodos
}
})
}
render() {
const todoItems = this.state.todos.map(item => <TodoItem key={item.id} item={item} handleChange={this.handleChange}/>)
return (
<div className="todo-list">
{todoItems}
</div>
)
}
}
export default App
and this is my ToDoItem component
function TodoItem(props) {
return (
<div className="todo-item">
<input
type="checkbox"
checked={props.item.completed}
onChange={() => props.handleChange(props.item.id)}
/>
<p>{props.item.text}</p>
</div>
)
}
export default TodoItem

Issue
You are mutating your state objects. When you don't return new object references React doesn't consider the value to be different and bails on rerendering with updated values.
if (todo.id === id) {
todo.completed = !todo.completed // <-- state mutation!
}
return todo // <-- same todo object reference
Solution
You need to also shallow copy any nested state you are updating.
handleChange(id) {
this.setState((prevState) => ({
todos: prevState.todos.map(todo => todo.id === id ? {
...todo, // <-- shallow copy todo
completed: !todo.completed, // <-- update completed property
} : todo)
});
}

Related

Update state in class from const

I'm new to React JS and I'm coding a really simple task manager. So, I have all tasks in state element of MyTodoList class (each task has: id, name, description, completed). Then I draw each task separately with Task constant.
I want to implement changing buttons below every task (if task is completed button should be "Done", if not - "Not done").
I do not understand how I can update "completed" attribute (which is in MyTodoList class in state) from const Task.
Would be grateful for any hint!
Code:
import logo from './logo.svg';
import './App.css';
import React from 'react';
function DoneButton({onClick}) {
return (
<button onClick={onClick}>
Done
</button>
);
}
function NotDoneButton({onClick}) {
return (
<button onClick={onClick}>
Not done
</button>
);
}
const Task = ({id, name, description, completed}) => {
const handleDoneClick = () => {
completed= false //something different should be here
}
const handleNotDoneClick = () => {
completed= true //something different should be here
}
let button;
if (completed) {
button = <DoneButton onClick={handleDoneClick} />
} else {
button = <NotDoneButton onClick={handleNotDoneClick} />
}
return (
<div className='task'>
<h3>{name}</h3>
<div>{description}</div>
<div>{completed}</div>
{button}
</div>
)
}
class MyTodoList extends React.Component {
state = {
tasks: [
{
id: 1,
name: 'Walk the dog',
description: 'Have to walk the dog today',
completed: false,
},
],
}
render () {
return(
<div>
<header><h1>TO-DO</h1></header>
<div>{this.state.tasks.map(task => <Task id={task.id} name={task.name}
description={task.description} completed={task.completed}/>)}
</div>
</div>
)
}
}
const App = () => {
return (
<MyTodoList />
)
}
export default App;
You should never re-assign parameters unless it is the only solution you have, but you should definitely never re-assign parameters which you plan to depend on in the render method.
The proper solution would be this:
import React, { useState } from 'react';
...
const Task = ({ id, name, description, completed }) => {
const [isCompleted, setIsCompleted] = useState(completed);
const handleDoneClick = () => {
setIsCompleted(true);
};
const handleNotDoneClick = () => {
setIsCompleted(false);
};
let button;
if (isCompleted) {
button = <DoneButton onClick={handleDoneClick} />;
} else {
button = <NotDoneButton onClick={handleNotDoneClick} />;
}
return (
<div className="task">
<h3>{name}</h3>
<div>{description}</div>
<div>{isCompleted}</div>
{button}
</div>
);
};
You need to use local state, in which you will set the initial value (completed, or not completed) which you are receiving from props, and then change the state, and not the parameter. Furthermore, continue using the state value of your completed (isCompleted) so React will react to its change.
This is not the final solution though, as this will only keep the local change of the task, and not change the task status in tasks list.
Basically, if you component A holds the tasks and their complete status, you need to create a method in the component A which will modify the respective task by ID, to the correct status. Then you need to pass the respective method to component B which will call the method and pass along the id and complete status (true / false) The method which is assigned in component A will then look through the list of tasks, find the proper task by ID, and assign its new completed value you passed from component B. After that, react does its thing and automatically updates completed prop you passed to component B
Working snippet:
function DoneButton({ onClick }) {
return <button onClick={onClick}>Done</button>;
}
function NotDoneButton({ onClick }) {
return <button onClick={onClick}>Not done</button>;
}
const Task = ({ id, name, description, completed, onTaskClick }) => {
const handleDoneClick = () => {
onTaskClick(id, false);
};
const handleNotDoneClick = () => {
onTaskClick(id, true);
};
let button;
if (completed) {
button = <DoneButton onClick={handleDoneClick} />;
} else {
button = <NotDoneButton onClick={handleNotDoneClick} />;
}
return (
<div className="task">
<h3>{name}</h3>
<div>{description}</div>
<div>{completed}</div>
{button}
</div>
);
};
const MyTodoList = () => {
const [tasks, setTasks] = React.useState([
{
id: 1,
name: 'Walk the dog',
description: 'Have to walk the dog today',
completed: false,
}
]);
const onTaskClick = React.useCallback(
(id, isCompleted) => {
const updatedTasks = [...tasks].map((task) => {
if (task.id === id) {
return {
...task,
completed: isCompleted,
};
}
return task;
});
setTasks(updatedTasks);
},
[tasks]
);
return (
<div>
<header>
<h1>TO-DO</h1>
</header>
<div>
{tasks.map((task) => (
<Task onTaskClick={onTaskClick} id={task.id} name={task.name} description={task.description} completed={task.completed} />
))}
</div>
</div>
);
};
const App = () => <MyTodoList />;
ReactDOM.render(<App />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>

React rendering JSON nested objects

I have this code which works perfectly:
componentDidMount() {
fetch('https://services2.arcgis.com/sJvSsHKKEOKRemAr/arcgis/rest/services/Bigfoot%20Locations/FeatureServer/0/query?where=1%3D1&outFields=*&outSR=4326&f=json')
.then((response) => {
return response.json();
})
.then((myJson) => {
this.setState({data: myJson.features[0].attributes.STATE_NAME})
console.log(this.state.data)
});
}
render() {
return (
<div className = ''>
{this.state.data}
</div>
)
}
}
However when I try to make the data set in state more general so that I can render whatever I want like this:
componentDidMount() {
fetch('https://services2.arcgis.com/sJvSsHKKEOKRemAr/arcgis/rest/services/Bigfoot%20Locations/FeatureServer/0/query?where=1%3D1&outFields=*&outSR=4326&f=json')
.then((response) => {
return response.json();
})
.then((myJson) => {
this.setState({data: myJson.features})
console.log(this.state.data)
});
}
render() {
return (
<div className = ''>
{this.state.data[0].attributes.STATE_NAME}
</div>
)
}
}
I get "Cannot read property STATE_NAME of undefined. The only change is that I tried to access the object in the render method instead of ComponentDidMount. What's the issue here?
In your component, the render() function is being called before the data is populated, even though componentDidMount() will run before the first render.
What you need is to store an intermediate loading state in your react state to indicate that the data has not yet arrived.
class RENAME_ME extends Component {
state = {
loaded: false,
data: [],
};
componentDidMount() {
fetch(
"https://services2.arcgis.com/sJvSsHKKEOKRemAr/arcgis/rest/services/Bigfoot%20Locations/FeatureServer/0/query?where=1%3D1&outFields=*&outSR=4326&f=json"
)
.then((response) => {
return response.json();
})
.then((myJson) => {
this.setState({
data: myJson.features[0].attributes.STATE_NAME,
loaded: true,
});
console.log(this.state.data);
});
}
render() {
// Data is still loading, display an intermediate message
if (!this.state.loaded) {
return <p>Loading...</p>;
}
return <div className="">{this.state.data}</div>;
}
}
You shouldn't read from the state until it's present:
render() {
return (
<div className = ''>
{(this.state.data && this.state.data.length) ? this.state.data[0].attributes.STATE_NAME : `still loading, or maybe an error`}
</div>
)
}
Only display the state when it is present so this condition has 2 parts.
First part(this.state.data) is only true when the data is saved in the state so the next part(this.state.data[0].attributes.STATE_NAME) runs after that
render() {
return (
<div className = ''>
{this.state.data && this.state.data[0].attributes.STATE_NAME}
</div>
)
}
}
Your state 'data' is not properly initialized to handle object maybe
are they initialized like this?
this.state = {
data: []
You can render the value whenever it is present by
{this.state.data[0].attributes && this.state.data[0].attributes.STATE_NAME}

React Map json data and create a dropdown

I have json data passed as props from the Redux store, the json has this format:
{
"label1.label2.label3": {
"option1":[
],
"option2": "value",
"option3": [
],
...
}
...
}
I need to split the label part and create a nested menu from the data as follows:
label1
label2
label3
option1
value of option1
option2
value of option2
option3
...
I couldn't figure out how to map into the data, my component code looks like this:
class MyDropdown extends React.Component {
componentDidMount(){
//A component dispatches ACTIONS
this.props.dispatch(fetchDataWithRedux());
}
render(){
const {error, loading, elements} = this.props;
if (loading){
return <div>Loading...</div>;
}
if (error){
return <div> Error! {error.message}</div>;
}
console.log(this.props.elements); //outputs "undefined"
return(
<div>
{this.props.elements && this.props.elements.map(this.createMenu)}
</div>
);
}
createMenu() {
return this.props.elements.map((item) => {
return(
);
});
}
}
const mapStateToProps = state => ({
elements: state.items,
loading: state.loading,
error: state.error
});
export default connect(mapStateToProps)(MyDropdown);
I'm getting real close with this. It's pretty tricky to get the nesting right though.
const data = {
"label1.label2.label3": {
"option1":"value1",
"option2": "value2",
"option3": "value3"
},
"label1.label2.label3.label4": {
"option1":"value1",
"option2": "value2"
},
}
class App extends React.Component {
createMenu = () => {
const options = Object.keys(data).reduce( (options, key, i) => {
const d = data[key];
let levels = key.split('.').map( (label, i) => {
return {
label: label,
options: []
};
});
levels[levels.length -1].options = Object.keys(d).map( option => {
return {
label: option,
value: d[option]
}
});
options.push(levels);
return options;
}, []);
const mapOptions = o => {
let menu = [];
o.forEach( (option, i) => {
if(!option.options.length) {
// Nest next option
menu.push(
<li>
{option.label}
</li>
);
}else {
// display options
menu.push(
<li>
{option.label}
{option.options.map( nested => {
return <li>{nested.label}: {nested.value}</li>
})}
</li>
);
}
});
return menu;
};
return options.map( option => {
return mapOptions(option);
});
};
render() {
return (
<div>
{this.createMenu()}
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('root'));
li li {
margin-left: 15px;
}
<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>

Can't access JSON object information React/Redux

Feels like I'm missing something obvious here - but I can't figure out how to access my JSON data. I have a Container component:
class About extends Component {
componentDidMount(){
const APP_URL = 'http://localhost/wordpress/'
const PAGES_URL = `${APP_URL}/wp-json/wp/v2/pages`
this.props.fetchAllPages(PAGES_URL, 'about')
}
render(){
return (
<div>
<Header/>
<div className="bg">
<div className="home-wrapper">
<h1>AAAAABBBBBOOOOUUUUUT</h1>
<Counter/>
<AboutInfo />
</div>
</div>
<Footer/>
</div>
)
}
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({ fetchAllPages }, dispatch)
}
export default connect(null, mapDispatchToProps)(About);
And a Smart component:
class AboutInfo extends Component {
render(){
console.log(this.props.page);
console.log(this.props.page.id);
return (
<div>
<h1>This is ID: {this.props.page.id}</h1>
</div>
)
}
}
const mapStateToProps = ({ page }) => {
return { page }
}
export default connect(mapStateToProps)(AboutInfo);
My action:
export const fetchAllPages = (URL, SLUG) => {
var URLEN;
if(!SLUG){
URLEN = URL
} else {
URLEN = URL + "?slug=" + SLUG
}
return (dispatch) => {
dispatch(fetchRequest());
return fetchPosts(URLEN).then(([response, json]) => {
if(response.status === 200){
if(!SLUG) {
dispatch(fetchPagesSuccess(json))
} else {
dispatch(fetchPageBySlugSuccess(json))
}
} else {
dispatch(fetchError())
}
})
}
}
const fetchPageBySlugSuccess = (payload) => {
return {
type: types.FETCH_PAGE_BY_SLUG,
payload
}
}
My reducer:
const page = (state = {}, action) => {
switch (action.type) {
case FETCH_PAGE_BY_SLUG:
console.log(action.paylod)
return action.payload
default:
return state
}
}
This gives me:
When I console.log(this.props.page) in my AboutInfo component, it prints the object, but when I print console.log(this.props.page.id) it gives me undefined. Why can't I print the JSON content? Thanks!
page is an array and hence this.props.page.id is undefined. You might want to access the first element in array in which case you would do
this.props.page[0].id
but you might also need to add a test, since before the response is available you will be trying to access page[0].id and it might break.
You could instead write
this.props.page && this.props.page[0] && this.props.page[0].id
Getting data from the store is async So you must adding loading varibale on your reducer
class AboutInfo extends Component {
render(){
if(this.props.loading) return (<div>loading</div>);
return (
<div>
<h1>This is ID: {this.props.page.id}</h1>
</div>
);
}
}
const mapStateToProps = ({ page, loading }) => {
return { page, loading }
}
on your action try returing
json.page[0]
That is because page is an array and the id is a property of its 1st element.
So use this.props.page[0].id
If the logged object in your screenshot is the this.props.page then you will need and additional .page as that is also a part of the object this.props.page.page[0].id

React function is not defined

I am trying to create a react component with imported data from Google API. I can see the code is working in the console.log but when I try to use that code in React render method, I am not getting anything. When I move my function inside the class it comes up as the function not defined. I cannot understand why?
function handleTouchTap() {
console.log('CHIP selected');
authorize();
}
function handleAccounts(response) {
console.log(response.result.username);
var username = response.result.username
console.log(username);
}
function authorize(event) {
var useImmidiate = event ? false : true;
var authData = {
client_id: CLIENT_ID,
scope: SCOPES,
immidiate: useImmidiate
};
gapi.auth.authorize(authData, function (response) {
gapi.client.load('analytics', 'v3').then(function () {
console.log(response);
gapi.client.analytics.management.accounts.list().then(handleAccounts);
});
});
}
class Chips extends React.Component {
render() {
return (
<div style={styles.wrapper}>
<Chip
onTouchTap={handleTouchTap}
style={styles.chip} >
<Avatar icon={<FontIcon className="material-icons">perm_identity</FontIcon>} />
Login
</Chip>
<Chip
style={styles.chip} >
<Avatar icon={<FontIcon className="material-icons">account_circle</FontIcon>} />
{this.username}
</Chip>
</div>
);
}
}
In most cases, when you want to render something that might change, you want to add it to the state. That way when you call setState the component knows it needs to rerender and show the changes.
Here I added the functions as component methods, so that you can call this.setState on the result. Ideally you would probably do this with redux and use actions but this will work as a self contained component.
class Chips extends React.Component {
handleTouchTap = () => {
console.log('CHIP selected');
this.authorize();
}
handleAccounts = (response) => {
var username = response.result.username;
this.setState({
username
});
}
authorize = (event) => {
var useImmidiate = event ? false : true;
var authData = {
client_id: CLIENT_ID,
scope: SCOPES,
immidiate: useImmidiate
};
gapi.auth.authorize(authData, (response) => {
gapi.client.load('analytics', 'v3').then(() => {
console.log(response);
gapi.client.analytics.management.accounts.list()
.then(this.handleAccounts);
});
});
}
render() {
return (
<div style={styles.wrapper}>
<Chip
onTouchTap={this.handleTouchTap}
style={styles.chip}>
<Avatar icon={<FontIcon className="material-icons">perm_identity</FontIcon>} />
Login
</Chip>
<Chip
style={styles.chip} >
<Avatar icon={<FontIcon className="material-icons">account_circle</FontIcon>} />
{this.state.username}
</Chip>
</div>
);
}
}