I'm trying to change the state of only one specific array item from the reviews array. How can this be done? This code doesn't seem to work:
this.setState({
reviews[2].current: true
});
Here's the full code:
import React, { Component } from "react";
import { render } from "react-dom";
const reviewsInit = [
{
name: "Peter Lahm",
current: null
},
{
name: "Simon Arnold",
current: null
},
{
name: "Claire Pullen",
current: null
}
];
class App extends Component {
constructor() {
super();
this.state = {
name: "React",
reviews: reviewsInit
};
}
change = () => {
this.setState({
reviews[2].current: true
});
};
render() {
return (
<div>
{console.log(this.state.reviews[2].current)}
<button onClick={this.change}>click me</button>
</div>
);
}
}
render(<App />, document.getElementById("root"));
Demo: https://stackblitz.com/edit/react-tbryf5
As you can probably tell I'm new to react! Thanks for any help here
For some context, React detects state change when reference of the state object changes. It does not track deep changes happening in array or the object.
Solution
We need to make another variable with same data (mostly destructuring). Change the value needed. And assign that to state again.
For Object
this.setState({...oldState, keyToChange: 'newValue'});
For Array
const temp = [...oldState];
temp[index] = 'newValue';
this.setState(temp);
Hope it helps.
It's common for an Array state to copy first then update one of its value
change = () => {
const result = [...this.state.reviews];
result[2].current = true;
this.setState({reviews: result});
};
import React, { Component } from "react";
import { render } from "react-dom";
const reviewsInit = [
{
name: "Peter Lahm",
current: null,
},
{
name: "Simon Arnold",
current: null,
},
{
name: "Claire Pullen",
current: null,
},
];
class App extends Component {
constructor() {
super();
this.state = {
name: "React",
reviews: reviewsInit,
};
}
change = () => {
const prevState = [...this.state.reviews];
prevState[2].current = true;
this.setState({
reviews: prevState,
});
};
render() {
return (
<div>
{console.log(this.state.reviews[2].current)}
<button onClick={this.change}>click me</button>
</div>
);
}
}
render(<App />, document.getElementById("root"));
Related
This is a simple TO-DO app in react in which App.js takes data from TodosData.js and the list is shown with the component TodoItem.js. Now the checkboxes and data can be viewed when rendered. But when I click on the checkbox it doesn't work. I tried console logging handleChange function which seems to work. It seems like there maybe problems inside the handleChange function which I can't figure out.
I am following a freecodecamp tutorial on YT and I also checked it several times but can't find the problem here.
App.js code:
import React from 'react';
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 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(itemEach => <TodoItem key = {itemEach.id} itemEach = {itemEach}
handleChange = {this.handleChange} />)
return (
<div className = "todo-list">
{todoItems}
</div>
)
}
}
export default App;
TodoItem.js code:
import React from 'react';
function TodoItem(props) {
return(
<div className = "todo-item">
<input type = "checkbox"
checked={props.itemEach.completed}
onChange={() => props.handleChange(props.itemEach.id)}
/>
<p>{props.itemEach.text}</p>
</div>
)
}
export default TodoItem
TodosData.js code:
const todosData = [
{
id: 1,
text: "Take out the trash",
completed: true
},
{
id: 2,
text: "Grocery shopping",
completed: false
},
{
id: 3,
text: "Clearn gecko tank",
completed: false
},
{
id: 4,
text: "Mow lawn",
completed: true
},
{
id: 5,
text: "Catch up on Arrested Development",
completed: false
}
]
export default todosData
Is there a better way to implement this? This way of doing checkbox seems quite complicated for a beginner like myself. Also how can I improve this code?
You are mutating the state in your handleChange function. Hence it gets the prevState twice. Once for the original previous state, next for the update that you make inside the handleChange.
You can probably lose the reference, by spreading the todo from state like this.
this.setState(prevState => {
const updatedTodos = prevState.todos.map(todo => {
const resTodo = { ...todo };
if (todo.id === id) {
resTodo.completed = !resTodo.completed;
}
return resTodo;
});
return {
todos: updatedTodos
};
});
Here's a working codesandbox
I am building a recipe app and I have an api that fetches me recipes based on what i type in. the issue is that whenever i type the search phrase and search, it makes the state super unstable by sending in insane amounts of objects into the state (normally it should be like 10-12 results. These objects are repeat of each other (you can see it in the screenshot i have attached). The code is provided below, can anyone show me why this might be so?
import React, { Component } from 'react';
import RecipeDisplay from '../RecipeDisplay/RecipeDisplay';
import Form from '../Form/Form';
import './RecipeUI.css';
import uuid from 'uuid/v4';
export default class RecipeUI extends Component {
constructor(props) {
super(props);
this.state = {
food: [ '' ],
RecipeUI: [ { title: '', thumbnail: '', href: '' } ]
};
this.search = this.search.bind(this);
}
search(x) {
this.setState({ food: x });
}
componentDidUpdate() {
let url = `https://api.edamam.com/search?q=${this.state
.food}&app_id=cf711&app_key=b67d194436b01d1f576aef`;
fetch(url)
.then((response) => {
return response.json();
})
.then((data) =>
data.hits.map((n) => {
let wow = {
key: uuid(),
title: n.recipe.label,
thumbnail: n.recipe.image,
href: n.recipe.url
};
this.setState({ RecipeUI: [ ...this.state.RecipeUI, wow ] });
console.log(this.state);
})
);
}
render() {
return (
<div className="RecipeUI">
<div className="RecipeUI-header">
<h1>Welcome to the Recipe Fetcher</h1>
<Form search={this.search} />
</div>
<div className="RecipeUI-RecipeDisplay">
{this.state.RecipeUI.map((recipe) => (
<RecipeDisplay
key={recipe.key}
title={recipe.title}
thumbnail={recipe.thumbnail}
ingredients={recipe.ingredients}
href={recipe.href}
/>
))}
</div>
</div>
);
}
}
Please, try this as you are concatenating the existing items in state with that of the items that are being brought from search results, the state has got lot of data. Assuming you need only the search results in state, here is the code below:
import React, { Component } from 'react';
import RecipeDisplay from '../RecipeDisplay/RecipeDisplay';
import Form from '../Form/Form';
import './RecipeUI.css';
import uuid from 'uuid/v4';
export default class RecipeUI extends Component {
constructor(props) {
super(props);
this.state = {
food: '',
RecipeUI: []
};
this.search = this.search.bind(this);
}
search(x) {
this.setState({ food: x });
}
componentDidUpdate() {
let url = `https://api.edamam.com/search?q=${this.state.food}&app_id=cf7165e1&app_key=
946d6fb34daf4db0f02a86bd47b89433`;
fetch(url).then((response) => response.json()).then((data) => {
let tempArr = [];
data.hits.map((n) => {
let wow = {
key: uuid(),
title: n.recipe.label,
thumbnail: n.recipe.image,
href: n.recipe.url
};
tempArr.push(wow);
});
this.setState({RecipeUI:tempArr})
});
}
render() {
return (
<div className="RecipeUI">
<div className="RecipeUI-header">
<h1>Welcome to the Recipe Fetcher</h1>
<Form search={this.search} />
</div>
<div className="RecipeUI-RecipeDisplay">
{this.state.RecipeUI.map((recipe) => (
<RecipeDisplay
key={recipe.key}
title={recipe.title}
thumbnail={recipe.thumbnail}
ingredients={recipe.ingredients}
href={recipe.href}
/>
))}
</div>
</div>
);
}
}
i have a an array of data in a file named 'external-data.js' like this
``
export const mydata = [
{
name: "john",
age: 20,
man: true
},
{
name: "julia",
age: 22,
man: false
}
];
``
and then i import the data in my 'reactjs' app and i tried destructuring it like so
``
import React, {component} from 'react';
import { mydata } from 'external-data.js';
class HumanApp extends Component {
state = {
myNewData: [...mydata]
}
componentDidMount() {
this.changeData();
}
const changeData = () => {
myNewData.map(item => item.name = 'boyka');
console.log("state Data: "+myNewData[0].name);
console.log("original Data:"+Mydata[0].name);
}
render() {
return (
....
);
}
};
export default HumanApp;
``
and then i expected to get: " state Data: boyka" and "original Data: john" but it seems that my changeData function also changed the original array and i get "original Data: boyka"
state = {
myNewData: [
...mydata.map(data => { ...data })
]
}
There you go:
import React, { Component } from "react";
import { mydata } from "./external-data.js";
class App extends Component {
state = {
myNewData: [...mydata]
};
componentDidMount() {
this.changeData();
}
changeData = () => {
this.setState(
(prevState) => {
const myNewData = { ...prevState.myNewData };
this.state.myNewData.forEach((item) => {
item.name = "boyka";
});
return {
myNewData
};
},
() => {
console.log(this.state.myNewData);
}
);
};
render() {
return <div>Hii</div>;
}
}
export default App;
You cannot mutate the state directly!! You need to change the state using useState() like the example above.
I use the dropdown in react js app but onChange is not triggering
my code is
import React from "react";
import PropTypes from "prop-types";
import Dropdown from 'react-dropdown';
const options = [
{ value: 'one', label: 'One' },
{ value: 'two', label: 'Two', className: 'myOptionClassName' },
];
class WebDashboardPage extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
quan = (event)=> {
console.log("Option selected:");
this.setState({ value: event.target.value });
};
render() {
return(
<b><Dropdown className="dropdownCss" options={options} onChange={e =>
this.quan(e.target.value)} /></b>
);
}
when I click the items in dropdown it shows the error
"TypeError: Cannot read property 'quan' of undefined"
I'm a newbie to react
thanks in advance
There is no issue with the react-dropdown library. Here is the code sandbox that I've set up and corrected OP's code. It works.
import React from "react";
import Dropdown from "react-dropdown";
import "react-dropdown/style.css";
const options = [
{ value: "one", label: "One" },
{ value: "two", label: "Two", className: "myOptionClassName" }
];
const defaultOption = options[0];
class WebDashboardPage extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedValue: ""
};
}
quan = value => {
this.setState({ selectedValue: value });
};
render() {
return (
<Dropdown options={options} value={defaultOption} onChange={this.quan} />
);
}
}
export default WebDashboardPage;
You should just do it this way:
<Dropdown className="dropdownCss" options={options} onChange={this.quan} />
Try this:
class WebDashboardPage extends React.Component {
constructor(props) {
super(props);
this.state = { value: '' }
this.quan = this.quan.bind(this);
}
quan(event) {
console.log("Option selected:");
this.setState({ value: event.target.value });
};
render() {
return(
<div><Dropdown className="dropdownCss" options={options} onChange={this.quan} /></div>
);
}
It seems the issue is with the react-dropdown component itself. You'll need to file an issue there.
react-dropdown component might not be using this.props.onChange somewhere or might be using problematically.
Or, it's probably, the component requires value state which have not defined?
this.state = {
value: ''
}
And was causing the issue?
The dropdown dependency you are using does not fire onChange with event as argument instead it fires onChange with the selected option.Try changing
onChange={e =>
this.quan(e.target.value)}
to
onChange={this.quan}
and change quan to
quan = (selectedOption)=> {
console.log("Option selected:"+selectedOption.value);
this.setState({ value: selectedOption.value });
};
I have tried it on my machine and it wroks perfectly. Also next important thing is don't put options the way you are doing instead put it on state. my final code is
class WebDashboardPage extends Component {
constructor(props) {
super(props);
const options = [
{
value: 'one',
label: 'One'
}, {
value: 'two',
label: 'Two',
className: 'myOptionClassName'
}
];
this.state = {options}
}
quan = (selectedOption) => {
console.log("Option selected:" + selectedOption.value);
this.setState({value: selectedOption.value});
};
render() {
return (<b><Dropdown className="dropdownCss" options={this.state.options} onChange={this.quan}/></b>);
}
}
I only did a little refactoring to the code. The main change is in how Dropdown handles change. When you pass in a function to handleChange, Dropdown calls the function internally and passes the selected object to it, so you all you needed to do was create a handler method that has one parameter which you'll use to update the state. I also set an initial state for value. Here's is a demo https://codesandbox.io/s/4qz7n0okyw
import React, { Component, Fragment } from "react";
import ReactDOM from "react-dom";
import Dropdown from "react-dropdown";
const options = [
{ value: "one", label: "One" },
{ value: "two", label: "Two", className: "myOptionClassName" }
];
class WebDashboardPage extends Component {
state = {
value: {}
};
quan = value => {
console.log("Option selected:", value);
this.setState({ value });
};
render() {
return (
<Fragment>
<Dropdown
className="dropdownCss"
options={options}
onChange={this.quan}
/>
</Fragment>
);
}
}
export default WebDashboardPage;
Change to
onChange={this.quan}, also in the initial state you should state your this.state.value
this.state = {
value: ''
}
also try to learn it on html element, not on jsx
Reading around, I see that initializing state from props in the getInitialState()/constructor can be an anti-pattern.
What is the best way of initializing state from props and managing to be consistent?
As you can see below, I'm trying to initialize my "Card" component so that I may have a likeCount and isLikedByMe states initialized. I do this so that I may have a custom like counter displayed and the text of the Like button to change, by resetting the state.
At this point, I'm doing this in the constructor, but that is the wrong way to do it. How should I manage this?
import * as React from "react";
import { CardLikeButton } from "./buttons";
export enum CardType {
None = 0,
Text,
Image
}
export interface CardMedia {
text?: string;
imageUrl?: string;
}
export interface CardDetails {
isLikedByMe: boolean;
likeCount: number;
}
export interface CardParams extends React.Props<any> {
cardType: number;
cardId: string;
cardMedia: CardMedia;
cardDetails: CardDetails;
}
export class Card extends React.Component<CardParams, CardDetails> {
state: CardDetails;
constructor(props: CardParams) {
super(props);
console.log("in card constructor");
console.log("card type: " + props.cardType);
this.state = { // setting state from props in getInitialState is not good practice
isLikedByMe: props.cardDetails.isLikedByMe,
likeCount: props.cardDetails.likeCount
};
}
componentWillReceiveProps(nextProps: CardParams) {
this.setState({
isLikedByMe: nextProps.cardDetails.isLikedByMe,
likeCount: nextProps.cardDetails.likeCount
});
}
render() {
console.log("RENDERING CARD");
// console.dir(this.props.cardDetails);
// console.dir(this.props.cardMedia);
// console.dir(this.props.cardType);
if (this.props.cardType === CardType.Text) { // status card
return (
<div className="general-card">
<p>Text card.ID: {this.props.cardId}</p>
<p>{this.props.cardMedia.text}</p>
<CardLikeButton onButClick={this.likeButtonClicked} buttonText={this.state.isLikedByMe ? "Liked" : "Like"} isPressed={this.state.isLikedByMe}/>
<p>Like count: {this.state.likeCount}</p>
</div>
);
} else { //photo card
return (
<div className="general-card">
<p>Image card.ID: {this.props.cardId}</p>
<p> {this.props.cardMedia.text} </p>
<img src={this.props.cardMedia.imageUrl} />
<br/>
<CardLikeButton onButClick={this.likeButtonClicked} buttonText={this.state.isLikedByMe ? "Liked" : "Like"} isPressed={this.state.isLikedByMe}/>
<p>Like count: {this.state.likeCount}</p>
</div>
);
}
}
likeButtonClicked = () => {
console.log('in card => like button clicked!');
var _isLikedByMe = this.state.isLikedByMe;
var _likeCount = this.state.likeCount;
if (_isLikedByMe) {
_likeCount--;
} else {
_likeCount++;
}
_isLikedByMe = !_isLikedByMe;
this.setState({
isLikedByMe: _isLikedByMe,
likeCount: _likeCount
})
}
}
Here is the main list component:
/// <reference path="../../typings/index.d.ts" />
import * as React from "react";
import * as ReactDOM from "react-dom";
import {Card} from "./card";
import {CardParams, CardType, CardMedia, CardDetails} from "./card";
var card1: CardParams = {
cardType: CardType.Image,
cardId: "card1234",
cardDetails: {
isLikedByMe: false,
likeCount: 3
},
cardMedia: {
text: "some test text; badescuga",
imageUrl: "http://www9.gsp.ro/usr/thumbs/thumb_924_x_600/2016/06/19/738742-rkx1568-lucian-sinmartean.jpg"
}
};
var card2: CardParams = {
cardId: "card35335",
cardType: CardType.Text,
cardDetails: {
isLikedByMe: true,
likeCount: 1
},
cardMedia: {
text: "some test 2 text"
}
};
var cards = [card1, card2];
ReactDOM.render(
<div>
{
cards.map((item) => {
return (
<Card key={item.cardId} cardId={item.cardId} cardType={item.cardType} cardDetails={item.cardDetails} cardMedia={item.cardMedia}/>
);
})
}
</div>,
document.getElementById("mainContainer")
);
Without getting into working with Flux, or Redux, and focusing on your question.
IMHO, state and props need to be separated, where Card only gets props, and state is managed from above. Card component will get an event handler to raise once the like button has been clicked. You could either do the "like" logic inside the Card component, and just raise the event handler with the output of that logic, for example:
this.props.likeClicked(isLikedByMe, updatedLikeCount).
Or, do the whole logic in the parent component.
I would also wrap all cards in another component.
Example:
class Card extends React.Component {
constructor(props: CardParams) {
super(props);
}
render() {
return (
<div>
<button onClick={this.likeButtonClicked}>
{this.props.isLikedByMe ? 'Unlike' : 'Like'}
</button>
<p>Like count: {this.props.likeCount}</p>
</div>
)
}
likeButtonClicked = () => {
console.log('in card => like button clicked!');
var _isLikedByMe = this.props.isLikedByMe;
var _likeCount = this.props.likeCount;
if (_isLikedByMe) {
_likeCount--;
} else {
_likeCount++;
}
_isLikedByMe = !_isLikedByMe;
if (this.props.likeUpdated) {
this.props.likeUpdated({
cardId: this.props.cardId,
isLikedByMe: _isLikedByMe,
likeCount: _likeCount
})
}
}
}
class CardList extends React.Component {
constructor(props) {
super(props)
this.state = {
// Could use es6 map
cards: {123: {isLikedByMe: false, likeCount: 3},
124: {isLikedByMe: true, likeCount: 2}}
}
}
_onLikeUpdated({cardId, isLikedByMe, likeCount}) {
const cards = Object.assign({}, this.state.cards)
cards[cardId] = {isLikedByMe, likeCount}
this.setState({cards})
}
_getCards() {
return Object.keys(this.state.cards).map(cardId => {
return <Card key={cardId}
cardId={cardId}
likeUpdated={this._onLikeUpdated.bind(this)}
{...this.state.cards[cardId]} />
})
}
render() {
return <div>
{this._getCards()}
</div>
}
}
Fiddle: https://jsfiddle.net/omerts/do13ez79/