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

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' />

Related

Learning react with a click game, onClick won't fire. I think I'm just passing a prop *called* onClick

The Bit component is supposed to be my clickable, which should be incrementing the state due to my mine function in the Mine component.
function Bit(props) {
return (
<img src={logo} className="App-logo" alt="logo" onClick={props.onClick} />
)
}
class Mine extends React.Component {
constructor(props) {
super(props);
this.state = {
bitCoins: 0,
clickBonus: 1,
cps: 1,
}
}
mine() {
alert('here')
this.setState({
bitCoins: this.state.bitCoins + 1
})
console.log(this.state.bitCoins);
}
render() {
let status;
status = this.state.bitCoins
return (
<div>
<Bit onClick={() => this.mine()} />
</div>
<div className="text-primary">{status}</div>
)
}
}
What is returned from render in React cannot have sibling elements at the top level. So just wrapping what you're returning with <React.Fragment> (or a div or whatever else you choose) fixed it.
Also note that setState is asynchronous, so when you console.log immediately after calling it, you may not get the most up to date values.
class Mine extends React.Component {
constructor(props) {
super(props);
this.state = {
bitCoins: 0,
clickBonus: 1,
cps: 1,
}
}
mine() {
alert('here')
this.setState({
bitCoins: this.state.bitCoins + 1
})
console.log(this.state.bitCoins);
}
render() {
let status;
status = this.state.bitCoins
return (
<React.Fragment>
<div>
<button onClick={() => this.mine()}>Mine</button>
</div>
<div className="text-primary">{status}</div>
</React.Fragment>
)
}
}
ReactDOM.render(
<Mine />,
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>

How to implement Reconciliation concept in react?

I want to add a string to my list and I have a CounterComponent that works separately from HelloWordComponent, I set 1 for 'Microsoft', 2 for 'FaceBook' and 3 for 'React'; when I add 'yahoo' to first of the list, Counter for 'yahoo' set to 1 and react turns to 0.
I know I have to use unique key and I think {name} is qualified, but I don't know where to use key = {name} exactly?
class HelloWordComponent extends React.Component {
render() {
return <div>{this.props.name}</div>
}
}
class Counter extends React.Component {
constructor(){
super()
this.onPlusClick = this.onPlusClick.bind(this)
this.state = {count : 0}
}
onPlusClick(){
this.setState(prevState => ({count: prevState.count + 1}))
}
render(){
return <div>
{this.state.count}
<button onClick = {this.onPlusClick}>+</button>
</div>
}
}
class App extends React.Component{
constructor(){
super()
this.addName = this.addName.bind(this)
this.state = {
name: "Sara",
list:['Microsoft', 'FaceBook', 'React']
}
}
addName(){
this.setState(prevState =>({list: ['Yahoo', ...prevState.list]}))
}
render(){
return (
<div >
{this.state.name}
{this.state.list.map(name =>{
return <div>
<HelloWordComponent key = {name} name = {name}/>
<Counter/>
</div>
})}
<br/>
<button onClick= {this.addName}>add a Name</button>
</div>
);
}
}
ReactDOM.render(<App/>,document.getElementById("app"));
<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="app"> </div>
I found the right solution of my problem, I have to set unique key (key = {name}) in my parent root element <div key = {name}> so the render method change to:
render(){
return (
<div >
{this.state.name}
{this.state.list.map(name =>{
return <div key = {name}>
<HelloWordComponent name = {name}/>
<Counter/>
</div>
})}

How to render multiple component in reactjs, what i'm doing wrong?

First i have a function to fetch data from database then
if the data be changed, i will create list components.
but it didnt work, what i'm doing wrong?
console:
class TweetContainer extends React.Component{
constructor(props){
super(props);
this.state = {
tweetData:{},
tweetRender : [],
listTweet:[]
}
}
here is my function to fetch data from database
componentDidMount(){
fetch('http://localhost:5000/tweet')
.then(function(response) {
return response.json();
})
.then(result=>{
this.setState({
tweetData: result
}, ()=>console.log(this.state.tweetData));
});
}
my function to make list component
componentDidUpdate(){
this.state.tweetRender = this.state.tweetData.data.slice(1,6);
console.log(this.state.tweetRender);
this.state.listTweet = this.state.tweetRender.map((tweet)=><Tweet
linkAvatar={'/image/jennyshen.jpg'}
name={"Vuongxuan"}
userName={'#vuggg'}
tweetText={tweet.content} />);
console.log(this.state.listTweet);
}
render(){
return(
<div id="main">
<h2>Tweet</h2>
<div id="stream">
{this.state.listTweet}
</div>
</div>
);
}
}
i dont know what i'm doing wrong.
Accordingly to React docs, componentDidMount lifecycle most common use is for:
Updating the DOM in response to prop or state changes.
And you want to get and render the tweets, right? Not necessarily listen to updates.
For now a solution is remove your componentDidUpdate() method and change your `render´ method to:
render(){
var tweetRender = this.state.tweetData.data.slice(1,6);
return(
<div id="main">
<h2>Tweet</h2>
<div id="stream">
{listTweet.map((tweet, idx) =>
<Tweet
key={idx}
linkAvatar={'/image/jennyshen.jpg'}
name={"Vuongxuan"}
userName={'#vuggg'}
tweetText={tweet.content} />
)}
</div>
</div>
);
}
It's generally not a good idea to put React elements (JSX) inside your component state. You could instead just store the data in state, and derive the JSX from that data in the render method.
Example
class TweetContainer extends React.Component {
state = {
tweetData: [],
tweetRender: [],
listTweet: []
};
componentDidMount() {
setTimeout(() => {
this.setState({
tweetData: [
{
id: 1,
name: "foo",
username: "#foo"
},
{
id: 2,
name: "bar",
username: "#bar"
}
]
});
}, 1000);
}
render() {
return (
<div id="main">
<h2>Tweet</h2>
<div id="stream">
{this.state.tweetData.map(obj => (
<div key={obj.id}>
{obj.username} - {obj.name}
</div>
))}
</div>
</div>
);
}
}
ReactDOM.render(<TweetContainer />, 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>

How to connect this state array value to div element

I am learning React and I am stuck on the following syntax.
class App extends React.Component{
constructor(){
super()
this.state = {
array: [1,2]
}
this.add = this.add.bind(this)
}
add(){
this.setState = {
array:[5,4]
}
}
render(){
const arr = this.state.array.map((val) => {
return val
});
///how to connect arr to div target_here
return(
<div>
<button onClick={this.add}>Button</button>
<div id="target_here"></div>
<button>Button</button>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById("app"))
My goal is to attach the const arr to the id target_here. This is sample syntax of the problem I am facing so I really appreciate solutions without changing the structure of the syntax. Help please?
Here's a working example of what you're trying to acomplish:
class App extends React.Component {
constructor(){
super()
this.state = {
array: [1,2]
}
this.add = this.add.bind(this)
}
add() {
this.setState({
array: [5,4]
})
}
render(){
const list = this.state.array.map(value => {
return <li>{value}</li>
});
return(
<div>
<button onClick={this.add}>Button</button>
<div id="list">
<ul>{list}</ul>
</div>
<button>Button</button>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'))
JSFiddle Demo: https://jsfiddle.net/fwg2vz3u/1/
I didn't quite understand the problem exactly, but if you are trying to display the array, you would do:
return(
<div>
<button onClick={this.add}>Button</button>
<div id="target_here"></div>
{arr}
<button>Button</button>
</div>

react change the class of list item on click

I have a react element like this:
import React, { PropTypes, Component } from 'react'
class AlbumList extends Component {
constructor(props) {
super(props);
this.state = {'active': false, 'class': 'album'};
}
handleClick() {
if(this.state.active){
this.setState({'active': false,'class': 'album'})
}else{
this.setState({'active': true,'class': 'active'})
}
}
render() {
var album_list
const {user} = this.props
if(user.data){
list = user.data.filter(album => album.photos).map((album => {
return <div className={"col-sm-3"} key={album.id}>
<div className={this.state.class} key={album.id} onClick={this.handleClick.bind(this)}>
<div className={"panel-heading"}>{ album.name }</div>
<div className={"panel-body"}>
<img className={"img-responsive"} src={album.photo.source} />
</div>
</div>
</div>
}))
}
return (
<div className={"container"}>
<div className="row">
{list}
</div>
</div>
)
}
}
export default AlbumList
Here map gives the list of filter data as I wanted. Here what I am doing changes the class of all the list element if I click on one.
I am getting the class name from this.state.class
How can I change the class of only element that i have clicked..
Thanks in advance ...
I have considered it once.So you have so many divs and you want to know which is clicked.My way to solve this problem is to give a param to the function handleClick and you can get the dom of the div while you click the div.Like this:
array.map(function(album,index){
return <div onClick={this.handleClick}/>
})
handleClick(e){
console.log(e.target);
e.target.className = 'active';
...
}
Then you have a param for this function.While you can use the e.target to get the dom of your div which is clicked.
There are some mistake into your code about the state.class.
class AlbumList extends Component {
constructor(props) {
super(props);
this.state = {'active': false, 'class': 'album'};
}
handleClick(e) {
if(e.target.class === 'active'){
e.target.className = 'album'
}else{
e.target.className = 'active'
}
}
render() {
var album_list
const {user} = this.props
if(user.data){
list = user.data.filter(album => album.photos).map((album => {
return (
<div className={"col-sm-3"} key={album.id}>
<div className='active' key={album.id} onClick={this.handleClick.bind(this)}>
<div className={"panel-heading"}>{ album.name }</div>
<div className={"panel-body"}>
<img className={"img-responsive"} src={album.photo.source} />
</div>
</div>
</div>
)
}))
}
return (
<div className={"container"}>
<div className="row">
{list}
</div>
</div>
)
}
}
You can try this and tell me anything wrong.

Resources