Reordering list element in react js - reactjs

I am wondering how to re order a list element. Its like you have a list of an elements li and put the last element in the first place like the index of 10th would be placed in the index of 0
React.render( <div>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li> //When an event fires, this item would go up to the first index </div>, document.getElementById('example') );

Based on your comment on Abdennour answer (you need to update an item regardless of its position), you cannot do such operation with an array of simple numbers, you need to index your values:
class MyList extends Component {
render() {
return(
<ul>
{this.props.items.map((item ,key) =>
<li key={key}> {item}</li>
)}
</ul>
)
}
}
class App extends React.Component{
constructor(props) {
this.state= {
listItems: [{id: 1, val: '1'}, {id: 2, val: '2'}, {id: 2, val: '2'}, {id: 3, val: '3'}]
};
}
reverse = () => {
this.setState({
listItems: this.state.listItems.reverse()
});
}
// You can ignore this, simple put some random value somewhere
// In your case this would be the function that changes the value of one of the items, should of course be NOT random
changeRandom = () => {
const index = Math.floor(Math.random() * this.state.listItems.length);
const newList = this.state.listItems.slice();
newList[index] = Math.floor(Math.random() * 10).toString();
this.setState({
listItems: newList
})
}
render() {
return (
<div>
<div>
<MyList items={this.state.listItems.map(item => item.val)} />
</div>
<div>
<button onClick={reverse}>Reverse</button>
</div>
<div>
<button onClick={changeRandom}>Random Change</button>
</div>
</div>
)
}
}

So, i assume you have two React components: one for the list, and the other is the main component (App) which includes the list as well as the button of reversing the list.
class MyList extends React.Component {
render() {
return(
<ul>
{this.props.items.map((item ,key) =>
<li key={key}> {item}</li>
)}
</ul>
)
}
}
MyList.defaultProps= {items:[]};
class App extends React.Component{
state= {
listItems: ['1', '2', '3', '4']
};
onClick(e) {
e.preventDefault();
this.setState({
listItems: this.state.listItems.reverse()
});
}
render() {
return (
<div>
<div>
<MyList items={this.state.listItems} />
</div>
<div>
<button onClick={this.onClick.bind(this)}>Reverse</button>
</div>
</div>
)
}
}
ReactDOM.render(<App /> , document.getElementById('example'))
<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>
<section id="example" />

Related

sort items in state alphabetically

I have a class based React component that is using items in state and rendering result. Here is short snippet how I do this:
class Menu extends Component {
constructor(props) {
super(props);
this.state = {
items: props.items.edges,
someItems: props.items.edges,
}
}
render() {
if (this.state.items.length > 0) {
return (
<div className="container">
<div className="row">
{this.state.someItems.map(({ node }) => {
return (
<div key={node.id}>
<div>
render some data
</div>
</div>
)
})}
</div>
</div>
);
}
}
}
The data is received as objects inside an array, like this:
My question is would it be possible to sort these items alphabetically before being rendered? What would be the best approach for this?
The best approach is to sort the items before you set them to the state. You can use the built in Array.prototype.sort method in order to sort the items. You can use the String.prototype.localeCompare in order to compare strings alphabetically.
I don't know the expected structure of your data so here is a general solution.
class App extends React.Component {
constructor(props) {
super(props);
// Make a copy so as not to modify the original array directly
const sortedCopy = [...props.items];
sortedCopy.sort((a, b) => a.name.localeCompare(b.name));
this.state = {
items: sortedCopy,
};
}
render() {
return (
<div>
{this.state.items.map((item) => (
<p key={item.id}>
<div>Item - {item.name}</div>
</p>
))}
</div>
);
}
}
// Example items prop is out of order
const items = [
{ id: 0, name: "C" },
{ id: 1, name: "B" },
{ id: 2, name: "A" },
{ id: 3, name: "D" },
];
ReactDOM.render(<App items={items} />, document.getElementById("root"));
<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>

Re-render component based on object updating

I have the following pattern
class List {
list: string[] = [];
showList() {
return this.list.map(element => <div>{element}</div>);
}
showOptions() {
return (
<div>
<div onClick={() => this.addToList('value1')}>Value #1</div>
<div onClick={() => this.addToList('value2')}>Value #2</div>
<div onClick={() => this.addToList('value3')}>Value #3</div>
<div onClick={() => this.addToList('value4')}>Value #4</div>
</div>
);
}
addToList(value: string) {
this.list.push(value);
}
}
class App extends Component {
myList: List;
constructor(props: any) {
super(props);
this.myList = new List();
}
render() {
<div>
Hey this is my app
{this.myList.showOptions()}
<div>{this.myList.showList()}</div>
</div>
}
}
It shows my options fine, and elements are added to the list when I click on it. However, the showList function is never called again from App, thus not showing any update.
How can I tell the main component to rerenders when List is updated ? I'm not sure my design pattern is good. My goal is to manage what my class displays inside itself, and just call the display functions from other components.
We should always use state to rerender react component.
Not sure what you want to accomplish exactly but hopefully this will give you a general idea what Jim means with using state:
const Option = React.memo(function Option({
value,
onClick,
}) {
return <div onClick={() => onClick(value)}>{value}</div>;
});
const Options = React.memo(function Options({
options,
onClick,
}) {
return (
<div>
{options.map(value => (
<Option
key={value}
value={value}
onClick={onClick}
/>
))}
</div>
);
});
class List extends React.PureComponent {
state = {
options: [1, 2, 3],
selected: [],
};
showList() {
return this.list.map(element => <div>{element}</div>);
}
add = (
value //arrow funcion to bind this
) =>
this.setState({
options: this.state.options.filter(o => o !== value),
selected: [...this.state.selected, value],
});
remove = (
value //arrow funcion to bind this
) =>
this.setState({
selected: this.state.selected.filter(
o => o !== value
),
options: [...this.state.options, value],
});
render() {
return (
<div>
<div>
<h4>options</h4>
<Options
options={this.state.options}
onClick={this.add}
/>
</div>
<div>
<h4>choosen options</h4>
<Options
options={this.state.selected}
onClick={this.remove}
/>
</div>
</div>
);
}
}
const App = () => <List />;
//render app
ReactDOM.render(
<App />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Iterate Item Inside JSX React Native [duplicate]

could you please tell me how to render a list in react js.
I do like this
https://plnkr.co/edit/X9Ov5roJtTSk9YhqYUdp?p=preview
class First extends React.Component {
constructor (props){
super(props);
}
render() {
const data =[{"name":"test1"},{"name":"test2"}];
const listItems = data.map((d) => <li key={d.name}>{d.name}</li>;
return (
<div>
hello
</div>
);
}
}
You can do it in two ways:
First:
render() {
const data =[{"name":"test1"},{"name":"test2"}];
const listItems = data.map((d) => <li key={d.name}>{d.name}</li>);
return (
<div>
{listItems }
</div>
);
}
Second: Directly write the map function in the return
render() {
const data =[{"name":"test1"},{"name":"test2"}];
return (
<div>
{data.map(function(d, idx){
return (<li key={idx}>{d.name}</li>)
})}
</div>
);
}
https://facebook.github.io/react/docs/jsx-in-depth.html#javascript-expressions
You can pass any JavaScript expression as children, by enclosing it within {}. For example, these expressions are equivalent:
<MyComponent>foo</MyComponent>
<MyComponent>{'foo'}</MyComponent>
This is often useful for rendering a list of JSX expressions of arbitrary length. For example, this renders an HTML list:
function Item(props) {
return <li>{props.message}</li>;
}
function TodoList() {
const todos = ['finish doc', 'submit pr', 'nag dan to review'];
return (
<ul>
{todos.map((message) => <Item key={message} message={message} />)}
</ul>
);
}
class First extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [{name: 'bob'}, {name: 'chris'}],
};
}
render() {
return (
<ul>
{this.state.data.map(d => <li key={d.name}>{d.name}</li>)}
</ul>
);
}
}
ReactDOM.render(
<First />,
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>
Shubham's answer explains very well. This answer is addition to it as per to avoid some pitfalls and refactoring to a more readable syntax
Pitfall : There is common misconception in rendering array of objects especially if there is an update or delete action performed on data. Use case would be like deleting an item from table row. Sometimes when row which is expected to be deleted, does not get deleted and instead other row gets deleted.
To avoid this, use key prop in root element which is looped over in JSX tree of .map(). Also adding React's Fragment will avoid adding another element in between of ul and li when rendered via calling method.
state = {
userData: [
{ id: '1', name: 'Joe', user_type: 'Developer' },
{ id: '2', name: 'Hill', user_type: 'Designer' }
]
};
deleteUser = id => {
// delete operation to remove item
};
renderItems = () => {
const data = this.state.userData;
const mapRows = data.map((item, index) => (
<Fragment key={item.id}>
<li>
{/* Passing unique value to 'key' prop, eases process for virtual DOM to remove specific element and update HTML tree */}
<span>Name : {item.name}</span>
<span>User Type: {item.user_type}</span>
<button onClick={() => this.deleteUser(item.id)}>
Delete User
</button>
</li>
</Fragment>
));
return mapRows;
};
render() {
return <ul>{this.renderItems()}</ul>;
}
Important : Decision to use which value should we pass to key prop also matters as common way is to use index parameter provided by .map().
TLDR; But there's a drawback to it and avoid it as much as possible and use any unique id from data which is being iterated such as item.id. There's a good article on this - https://medium.com/#robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318
Try this below code in app.js file, easy to understand
function List({}) {
var nameList = [
{ id: "01", firstname: "Rahul", lastname: "Gulati" },
{ id: "02", firstname: "Ronak", lastname: "Gupta" },
{ id: "03", firstname: "Vaishali", lastname: "Kohli" },
{ id: "04", firstname: "Peter", lastname: "Sharma" }
];
const itemList = nameList.map((item) => (
<li>
{item.firstname} {item.lastname}
</li>
));
return (
<div>
<ol style={{ listStyleType: "none" }}>{itemList}</ol>
</div>
);
}
export default function App() {
return (
<div className="App">
<List />
</div>
);
}
import React from 'react';
class RentalHome extends React.Component{
constructor(){
super();
this.state = {
rentals:[{
_id: 1,
title: "Nice Shahghouse Biryani",
city: "Hyderabad",
category: "condo",
image: "http://via.placeholder.com/350x250",
numOfRooms: 4,
shared: true,
description: "Very nice apartment in center of the city.",
dailyPrice: 43
},
{
_id: 2,
title: "Modern apartment in center",
city: "Bangalore",
category: "apartment",
image: "http://via.placeholder.com/350x250",
numOfRooms: 1,
shared: false,
description: "Very nice apartment in center of the city.",
dailyPrice: 11
},
{
_id: 3,
title: "Old house in nature",
city: "Patna",
category: "house",
image: "http://via.placeholder.com/350x250",
numOfRooms: 5,
shared: true,
description: "Very nice apartment in center of the city.",
dailyPrice: 23
}]
}
}
render(){
const {rentals} = this.state;
return(
<div className="card-list">
<div className="container">
<h1 className="page-title">Your Home All Around the World</h1>
<div className="row">
{
rentals.map((rental)=>{
return(
<div key={rental._id} className="col-md-3">
<div className="card bwm-card">
<img
className="card-img-top"
src={rental.image}
alt={rental.title} />
<div className="card-body">
<h6 className="card-subtitle mb-0 text-muted">
{rental.shared} {rental.category} {rental.city}
</h6>
<h5 className="card-title big-font">
{rental.title}
</h5>
<p className="card-text">
${rental.dailyPrice} per Night · Free Cancelation
</p>
</div>
</div>
</div>
)
})
}
</div>
</div>
</div>
)
}
}
export default RentalHome;
Try this:
class First extends React.Component {
constructor (props){
super(props);
}
render() {
const data =[{"name":"test1"},{"name":"test2"}];
const listItems = data.map((d) => <li key={d.name}>{d.name}</li>;
return (
<div>
{listItems}
</div>
);
}
}

Trying to load multiple C3 charts in same react component

I am trying to map over an array and get a chart to appear alongside with each element, but it doesn't seem to work. This same code appeared once correctly, but no other time and I am not sure what I am missing.
I tried to change the id name to where it tags the chart and I did that by adding an index variable, but still not working
import React from 'react'
import c3 from '/c3.min.js'
class SearchedFood extends React.Component {
constructor(props) {
super(props)
this.state = {
}
this.graph = this.graph.bind(this)
}
graph(index) {
c3.generate({
bindto: '#class' + index,
data: {
columns: [
[1, 2, 3], [2, 3,4]
],
type: 'bar'
},
bar: {
width: {
ratio: 0.3
}
}
})}
render () {
return (
<div>
{this.props.foodResults.map((food, i) => {
return (
<div key={i}>
<label>{food.recipe.label}</label>
<img className="card-img-top" src={food.recipe.image} height="250" width="auto"></img>
<a href={food.recipe.url}>{food.recipe.source}</a>
<p>{food.recipe.dietLabels[0]}</p>
<div>
{food.recipe.ingredientLines.map((ingredient, i) => {
return (
<p key={i}>{ingredient}</p>
)
})}
</div>
<p>Calories {Math.floor(food.recipe.calories/food.recipe.yield)}</p>
<div id={`class${i}`}>{this.graph(i)}</div>
</div>
)
})}
</div>
)
}
}
export default SearchedFood
bindto: '#class' + index,/{this.graph...} isn't gonna work. React doesn't render directly/immediately to the DOM.
Looks like you can use elements with bindTo - your best bet is to use a ref
class SearchedFoodRow extends React.Component {
componentDidMount() {
c3.generate({
bindTo: this.element,
...
})
}
render() {
const { food } = this.props
return (
<div>
<label>{food.recipe.label}</label>
<img className="card-img-top" src={food.recipe.image} height="250" width="auto"></img>
<a href={food.recipe.url}>{food.recipe.source}</a>
<p>{food.recipe.dietLabels[0]}</p>
<div>
{food.recipe.ingredientLines.map((ingredient, i) => {
return (
<p key={i}>{ingredient}</p>
)
})}
</div>
<p>Calories {Math.floor(food.recipe.calories/food.recipe.yield)}</p>
<div ref={ element => this.element = element } />
</div>
)
}
}
and then
class SearchFood extends React.Component {
render() {
return (
<div>
{ this.props.foodResults.map((food, i) => <SearchedFoodRow key={i} food={food} />)}
</div>
)
}
}

Why is my component not getting re-rendered upon using setState and changing the value of state?

Why is it that the component Eachcartitem is not getting re rendered although I change the state. I have this fucntion which gets called from inside the Eachcartitem component:-
cartremover(a){
var cart1=cart;
var firstpart=cart.slice(0,a);
var secondpart=cart.slice(a+1,cart.length);
var final = firstpart.concat(secondpart);
this.setState({
cartstate:final,
abc:true
})
}
The Eachcartitem is used as follows in parent component:-
<div style={{float:'left',width:'65%'}}>
{
this.state.cartstate.map((cat) => (<Eachcartitem data={cat} index={this.state.cartstate.indexOf(cat)} cartremover={i=>this.cartremover()}/>))
}
<br></br><br></br>
</div>
And the Eachcartitem is as follows:-
class Eachcartitem extends React.Component{
constructor(props){
super(props);
this.state={
data:this.props.data
};
}
clicker(){
this.props.cartremover(this.props.index);
}
render(){
return(
<div className='cartdiv'>
<div style={{width:'100%',display:'inline'}}>
<h3 style={{width:'70%',float:'left',paddingLeft:'10px'}}>{this.state.data.productName}</h3>
<div style={{float:'right'}}>Rs.{this.state.data.productPrice}</div>
<div style={{width:'30%',float:'left',paddingLeft:'10px'}}>Store:{this.state.data.shopName}</div>
<div style={{width:'30%',float:'left',paddingLeft:'10px'}}>Quantity:{this.state.data.productQuantity}</div>
<br></br><br></br><br></br><br></br><br></br>
<div style={{width:'auto',float:'left',paddingLeft:'10px'}}>Variant:{this.state.data.variant.quantity}</div>
<br></br><br></br><br></br><br></br>
<div style={{width:'auto',float:'right',marginRight:'7px'}} onClick={()=>this.clicker()}>❌</div>
</div>
</div>
);
}
}
export default Eachcartitem
But for some reason the cartitem divs are not getting changed why is it so?
Its because you are not passing the index of the item to the function, here:
cartremover={i => this.cartremover()}
Write it like this:
cartremover={i => this.cartremover(i)}
You don't need to pass the index to child component, use this code:
this.state.cartstate.map((cat, i) => (
<Eachcartitem data={cat} cartremover={e => this.cartremover(i)} />
))
Now from Eachcartitem simply call that method: this.props.cartremover().
Better to use splice to remove the element at particular index, write the method like this:
cartremover(a){
let cart = [...this.state.cartstate];
cart.splice(a, 1);
this.setState({
cartstate: cart,
abc: true
})
}
Check working snippet:
const Temp = (props) => <div>
{props.name}
<button onClick={props.cartremover}>Delete</button>
</div>
class App extends React.Component {
constructor() {
super()
this.state = {cart: ['a', 'b', 'c', 'd', 'e']}
}
cartremover(a){
let cart = [...this.state.cart];
cart.splice(a, 1);
this.setState({
cart,
})
}
render() {
return (
<div>
{this.state.cart.map((cart, i) => (
<Temp key={cart} name={cart} cartremover={e => this.cartremover(i)}/>
))}
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'))
<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='app' />

Resources