print the updated version of the array in reactjs - reactjs

I'm trying to delete a data in array using the filter function which return a new array. The problem is how do I push the updated version of the array to the original version?, or if I can't do that, how do I print only the updated version?
here is my state:
export class App extends React.Component {
constructor() {
super();
this.state = {
todos: [
id: 1, nama: 'belajar', status: 'belum selesai',
id: 2, nama: 'kuliah', status: 'belum selesai',
id: 3, nama: 'sekolah', status: 'belum selesai',
id: 4, nama: 'makan', status: 'belum selesai'
]
};
this.state = { value: '' };
this.state = { isReady: false };
this.sayHello = this.sayHello.bind(this);
this.teken = this.teken.bind(this);
this.done = this.done.bind(this);
}
}
here is my code:
done(event) {
this.setState({ isReady: true });
var str = event.target.value;
var arr = str.split();
console.log(this.state.todos);
const list = todos.filter((todos) => todos.nama !== event.target.value);
console.log(list);
this.setState({ todos: list });
this.setState({ nama: event.target.value });
todos.push({
id: event.target.name,
nama: event.target.value,
status: 'selesai'
});
const find = todos.hasOwnProperty(event);
if (find) {
this.setState({ stat: find });
} else {
this.setState({ stat: find });
}
event.preventDefault();
}
and here is how I print my array
<ul className='list-group list-group-flush'>
{todos.map((todos) => {
if (todos.status === 'belum selesai')
return (
<li className='list-group-item'>
{todos.id} {todos.nama}
<button
value={todos.nama}
name={todos.id}
className='btn form-control form-control-sm col-sm-4 bg-light rounded-pill'
onClick={this.done}
>
Done {todos.id}
</button>
</li>
);
else
return (
<li className='list-group-item'>
<s>
{todos.id} {todos.nama}
</s>
</li>
);
})}
</ul>

You are very close. In order to update the list item HTML elements in your component you need to update the list of todos in your state.
done(event) {
// Copy to a new variable.
const nextTodos = this.state.todos.slice();
// Modify however you want.
nextTodos.push({ nama: 'new item' });
// Update the todos. You were missing this part!
this.setState({ todos: nextTodos });
}
In your render function reference this.state.todos like you are doing now.
In the component constructor, set the initial state.
constructor(props) {
super(props);
this.state = {
todos: [
// initial todo data
],
};
}

Related

how to push a new element into an array from the state

I'm trying to push in elements into an array called 'this.state.tags'. On the console, I see the elements pushing into the array. However, when I add something, the array comes out blank, when I add more items I only the see the previous items I've added. I'm not seeing the newest item I've pushed in.
I've done Object.assign([], this.state.tags) from the child component Grades.js. Then I pushed in 'this.state.newTag' and I've reset the state to that new result.
//From Grades.js, the child component
state = {
toggle: null,
newTag: '',
tags: []
}
addTags = (event) => {
event.preventDefault();
let newTagArr = Object.assign([], this.state.tags)
newTagArr.push(this.state.newTag)
this.setState({
tags: newTagArr
})
// this will pass on to the parent
this.props.filterTags(this.state.tags)
}
render() {
const { tags } = this.state
let tagList = tags.map((item, index) => {
return (
<li key={index} className="tagListItem">{item}</li>
)
})
return(
<div>
<ul className="tagList">{tagList}</ul>
<form onSubmit={this.addTags}>
<input
placeholder="Add a tag"
name="newTag"
onChange={this.handleInput}
style={{border: '0', borderBottom: '1px solid #000'}}
/>
</form>
</div>
)
}
// From App.js, the parent component
state = {
students: [],
filteredStudents: [],
filteredByTag: [],
search: '',
tag: '',
toggle: false
}
componentDidMount() {
axios.get('https://www.hatchways.io/api/assessment/students')
.then(result => {
let newArr = Object.assign([], result.data.students);
let newResult = newArr.map(elem => {
return {city: elem.city, company: elem.company, email: elem.email,
firstName: elem.firstName.toLowerCase(), lastName: elem.lastName.toLowerCase(),
grades: elem.grades, id: elem.id, pic: elem.pic, skill: elem.skill}
})
this.setState({
students: newResult
})
})
.catch(err => console.log(err))
}
tagFiltering = (param) => {
console.log(param)
this.state.students.push()
}
I expect the output to be ["tag1", "tag2", "tag3"]
Not ["tag1", "tag2"], when I've already typed in tag1, tag2 and tag3
Use ES2015 syntax :
this.setState({
tags: [...this.state.tags , this.state.newTag]
})
In react the state is immutable meaning that we have to provide new state object every time, we call the setState method.

Dynamic links firebase UI

I want to render a list of restaurants inside select tag with options so that the user can choose a restaurant.
What i try so far:
class Banner extends Component {
this.state = {
restaurant: "",
}
restaurantlist = () => {
var res=[]
var { restaurants } = this.props;
restaurants = restaurants.filter(rest => {
return rest.name.toUpperCase().indexOf(this.state.restaurant.toUpperCase()) !== -1 &&
rest.publish === true })
console.log(restaurants)
res = restaurants.map((item) => (
<li key={item.id}>{item.name}</li>))
return res;
}
<input onChange={(e)=>{ const restaurant = e.target.value;
this.setState({restaurant:restaurant})}}
type="text" name="restaurant" className="res__search"
placeholder="Restaurant"
/>
First you need some corrections with state:
this.state = {
restaurants: [],
// ...
}
You need restaurants as Array not as String.
This is a basic implementation of Select/Option with React:
class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
restaurants: [
{ id: 1, name: 'First' },
{ id: 2, name: 'Second' },
{ id: 3, name: 'Third' }
],
selected: 2,
};
}
handleChange = e => {
this.setState({
selected: e.target.value,
})
}
render() {
return (
<div>
<select value={this.state.selected} onChange={this.handleChange}>
{this.state.restaurants.map(x => <option value={x.id}>{x.name}</option>)}
</select>
<h4>State:</h4>
<pre>{JSON.stringify(this.state, null, 2)}</pre>
</div>
);
};
}
React.render(<Test />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.9/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/0.14.9/react-dom.min.js"></script>
<div id="app"></div>
Note:
Please read React documentation and also take a look at this example

ReactJS won't print an array in the order that it is stored?

I have an issue with my reactjs code where the render() function won't print an array in the order that it is stored in my state object.
Here's my code which is pretty simple:
import React from "react";
export default class DonationDetail extends React.Component {
constructor(props) {
super(props);
this.state = { content: [] };
}
componentDidMount() {
let state = this.state;
state.content.push({ food: "burger" });
state.content.push({ food: "pizza" });
state.content.push({ food: "tacos" });
this.setState(state);
}
addPaymentItem() {
const item = { food: "" };
let state = this.state;
state.content.unshift(item);
this.setState(state);
}
render() {
console.log(this.state);
let ui = (
<div>
<button type="button" onClick={() => this.addPaymentItem()}>
add to top
</button>
{this.state.content.map((item, key) => (
<input type="text" key={key} defaultValue={item.food} />
))}
</div>
);
return ui;
}
}
When you press the button add to top, a new item is placed to the front of the state.content array, which you can verify from the console.log(this.state) statement. But what's unusual is that the HTML that is generated does NOT add this new item to the top of the user interface output. Instead, another input field with the word taco is placed at the bottom of the list in the user interface.
Why won't ReactJS print my state.content array in the order that it is actually stored?
You can use the array index as key when the order of the elements in the array will not change, but when you add an element to the beginning of the array the order is changed.
You could add a unique id to all your foods and use that as key instead.
Example
class DonationDetail extends React.Component {
state = { content: [] };
componentDidMount() {
const content = [];
content.push({ id: 1, food: "burger" });
content.push({ id: 2, food: "pizza" });
content.push({ id: 3, food: "tacos" });
this.setState({ content });
}
addPaymentItem = () => {
const item = { id: Math.random(), food: "" };
this.setState(prevState => ({ content: [item, ...prevState.content] }));
};
handleChange = (event, index) => {
const { value } = event.target;
this.setState(prevState => {
const content = [...prevState.content];
content[index] = { ...content[index], food: value };
return { content };
});
};
render() {
return (
<div>
<button type="button" onClick={this.addPaymentItem}>
add to top
</button>
{this.state.content.map((item, index) => (
<input
type="text"
key={item.id}
value={item.food}
onChange={event => this.handleChange(event, index)}
/>
))}
</div>
);
}
}
ReactDOM.render(<DonationDetail />, 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>
Instead of:
componentDidMount() {
let state = this.state;
state.content.push({ food: "burger" });
state.content.push({ food: "pizza" });
state.content.push({ food: "tacos" });
this.setState(state);
}
Try
componentDidMount() {
this.setState(prevState => ({
content: [
...prevState.content,
{ food: "burger" },
{ food: "pizza" },
{ food: "tacos" },
]
}));
}
and
addPaymentItem() {
const item = { food: "" };
let state = this.state;
state.content.unshift(item);
this.setState(state);
}
to
addPaymentItem() {
this.setState(prevState => ({
content: [
{ food: "" },
...prevState.content,
]
}));
}

How to add an object in an array of objects? ReactJS?

My Project is, an array of objects where i get only the names and render on screen of form 3 in 3, with button next and previous change the names, and can to filter for letters.
I would want add a new value, typped on input and clicked in the button add.
My code button:
addItem = () => {
const inValue = {
id: 0,
name: this.state.input
}
this.setState({
filtered: this.state.filtered.concat(inValue),
currentPage: 0
})
}
I would want the value inserted in the filtered array.
My code all:
import React, { Component } from 'react';
class App extends Component {
constructor() {
super();
const peoples =[{id:0, name:"Jean"},
{id:1, name:"Jaha"},
{id:2, name:"Rido"},
{id:3, name:"Ja"},
{id:4, name:"Letia"},
{id:5, name:"Di"},
{id:6, name:"Dane"},
{id:7, name:"Tamy"},
{id:8, name:"Tass"},
{id:9, name:"Ts"},
{id:10, name:"Abu"},
{id:11, name:"Ab"}];
this.state = {
elementsPerPage:3,
currentPage:0,
peoples,
input: "",
filtered: peoples,
teste: '',
};
}
getValueInput = (evt) => {
const inputValue = evt.target.value;
this.setState({ input: inputValue });
this.filterNames(inputValue);
}
filterNames = (inputValue)=> {
const { peoples } = this.state;
this.setState({
filtered: peoples.filter(item =>
item.name.includes(inputValue)),
currentPage:0
});
const Oi = this.state.filtered.map(item=>item.name);
if(Oi.length<=0){
alert('Você está adicionando um nome')
}
console.log(Oi)
}
elementsOnScreen = () => {
const {elementsPerPage, currentPage, filtered} = this.state;
return filtered
.map((item) => <li key={item.id}> {item.name} <button onClick={() => this.remove(item.name)}> Delete </button> </li>)
.slice(currentPage*elementsPerPage, currentPage*elementsPerPage + elementsPerPage);
if(this.state.filtered.length < 1){
this.setState({currentPage: this.state.currentPage - 1})
}
}
remove = (id) => {
console.log(this.state.filtered.length)
if(this.state.filtered.length < 0){
this.setState({currentPange: this.state.currenPage - 1})
}
this.setState({filtered: this.state.filtered.filter(item => item.name !== id) })
}
nextPage = () => {
console.log(this.state.filtered)
const {elementsPerPage, currentPage, filtered} = this.state;
if ((currentPage+1) * elementsPerPage < filtered.length){
this.setState({ currentPage: this.state.currentPage + 1 });
}
}
previousPage = () => {
const { currentPage } = this.state;
if(currentPage - 1 >= 0){
this.setState({ currentPage: this.state.currentPage - 1 });
}
}
addItem = () =>{
const inValue = {id:0 ,name: this.state.input}
this.setState({filtered: this.state.filtered.concat(inValue), currentPage: 0})
}
render() {
return (
<div>
<button onClick={this.addItem}> Add </button>
<input type="text" onChange={ this.getValueInput }></input>
<button onClick={this.previousPage}> Previous </button>
<button onClick={this.nextPage}> Next </button>
<h3>Current Page: {this.state.currentPage}</h3>
<ul>Names: {this.elementsOnScreen()}</ul>
</div>
);
}
}
export default App;
You would have the array of objects contained within your state, then use setState
this.state = {
elementsPerPage:3,
currentPage:0,
peoples,
input: "",
filtered: peoples,
teste: '',
peoples: [
{id:0, name:"Jean"},
{id:1, name:"Jaha"},
{id:2, name:"Rido"},
{id:3, name:"Ja"},
{id:4, name:"Letia"},
{id:5, name:"Di"},
{id:6, name:"Dane"},
{id:7, name:"Tamy"},
{id:8, name:"Tass"},
{id:9, name:"Ts"},
{id:10, name:"Abu"},
{id:11, name:"Ab"}];
};
To update the peoples array, you would first need to create a copy of the peoples array, modify the copy, then use setState to update.
let { peoples } = this.state;
peoples.push({ id:12, name:"Jean"})
this.setState({peoples: peoples})
Looks like you are already updating your state with the typed input.
So in your add button you can get the state value and push it to your people array. Something like this:
addItem = () => {
const { inputValue, people } = this.state;
if (!inputValue) return; // check if inputValue has any value
people.push({ id: people.length+1, name: inputValue )} // I don't recommend using sequencial ids like this, you'd better have a handler to generate it for you
this.setState({ people, inputValue: '' }); // update people and clear input
}
Hope it helps

Inputs not changing when removing list items from state

I made a simple class that shows a list that you can add or remove li items into state. However, these li items contains input boxes.
Let's say there are 3 li items with 3 input boxes in it. You type something into first list item's input box, then you want to remove that li which contains your filled input.
Even if my index is correct react removes always the last item or I thought it removes the last item, maybe it removes the exact one with the correct index but preserves inputs' values. how can I fix this thing?
class DataTable extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [
{product: 'a', quantity: 0, price: 0},
],
};
}
render() {
if (!this.props.isOpen) {
return false;
}
const items = this.state.data.map((key, i) => {
return (
<li key={i}>
<input name="text" defaultValue={key.product}/>
<buttun className="btn" onClick={this.removeItem.bind(this, i)}/>
</li>
)
})
return (
<div>
<button className="btn" onClick={this.addItem.bind(this)}>Add Product</button>
<ul>
{items}
</ul>
</div>
)
}
addItem() {
const newState = update(this.state.data, {
$push: [{product: '', quantity: 0, price: 0}]
});
this.setState({
data: newState
})
}
removeItem(index) {
const newArray = update(this.state.data, {
$splice: [[index, 1]]
});
this.setState({
data: newArray
})
}
}
export default DataTable
Don't know if this is your problem but you are using the index of data as the key. This is only fine to do so when you don't modify the collection. Key must stay constant throughout, what's happening is that you remove an item and add another one and React thinks that input is the other one because it's key has changed.
constructor(props) {
super(props);
this.state = {
data: [
{product: 'a', quantity: 0, price: 0},
],
};
this.dataKey = 0;
render() {
if (!this.props.isOpen) {
return false;
}
const items = this.state.data.map((value) => {
return (
<li key={value.key}>
<input name="text" defaultValue={value.product}/>
<buttun className="btn" onClick={this.removeItem.bind(this, i)}/>
</li>
)
})
return (
<div>
<button className="btn" onClick={this.addItem.bind(this)}>Add Product</button>
<ul>
{items}
</ul>
</div>
)
addItem() {
const newState = update(this.state.data, {
$push: [{product: '', quantity: 0, price: 0, key: this.dataKey++}]
});
this.setState({
data: newState
})
}
removeItem(index) {
const newArray = update(this.state.data, {
$splice: [[index, 1]]
});
this.setState({
data: newArray
})
}
}
It just has to be something that is unique and constant. An Id for example would be good for this. https://facebook.github.io/react/docs/lists-and-keys.html

Resources