I'm just trying to update the state of totalItems and total price. I've created the logic within the cart class component below but I'm receiving the following errors:
Cart.js:24 Uncaught TypeError: Cannot read properties of undefined (reading 'length')
at Cart.render (Cart.js:24:1)
at finishClassComponent (react-dom.development.js:19752:1)
[Violation] 'message' handler took 177ms
I am assuming I need to include setState somewhere in each statement but I'm not sure where. Can you please assist?
class Cart extends Component{
constructor(props){
super(props)
this.state={
shoppingCart:[]
}
this.state = {
totalItems: 0,
totalPrice: 0
}
}
render(){
const cartItems = JSON.parse( localStorage.getItem('cart'));
const totalItems = this.state.cartItems.length;
const totalPrice = this.cartItems.map(item => item.amount).redeuce((prev, curr)=> prev + curr,0 );
return(<>
<div>
<h2>YOUR CART</h2>
<p># Of Items: <span>{totalItems}</span></p>
<p>Total Price: <span>{totalPrice}</span></p>
<p>Check Out</p>
</div>
<div className="container prod-cntr">
<div className="row prod-row">
{cartItems?.map((element) => (
<div className="col-lg-3 prod-col" key={element.id}>
<div className="card card-container">
<img
src={element.image}
alt="product img"
className="prod-img"
/>
<div className="card-body">
<p className="card-title">{element.product}</p>
<p className="card-text">{element.description}</p>
<p className ="quantity"><span className="decrease"><i className="fa-solid fa-minus"></i></span>Quantity: <span className ="increase"><i className="fa-solid fa-plus"></i> </span></p>
</div>
</div>
</div>
))}
</div>
<div>
</div>
</div>
</>)
}
}
export default Cart;
The state doesn't have an array named cartItems. So it gives error for this.state.cartItems.length. Do you mean this.state.shoppingCart.length?
Related
I have tried to access WP REST to React. Fetch method get data I have consoled and check. When I try to bind data to the frontend map function throws an error.
import React,{ Component } from 'react';
class HomePage extends Component{
constructor(props){
super(props);
this.state = {
loading:true,
Companies:[]
}
}
async componentDidMount(){
let data= fetch('https://example.co/wp-json/wp/v2/company?per_page=10').then((resp) =>{
resp.json().then((res)=>{
console.log(res);
this.setState({Companies:res,loading:false})
})
})
}
render() {
const Companies = this.state.Companies;
return (
<div>
<section className="selected-firms-banner" style={{backgroundImage: 'url("https://example.co/wp-content/themes/demotheme/images/Hero-Banner.jpg")'}}>
<div className="container">
<div className="banner-content">
<div className="row">
<div className="col-md-12 banner-title">
<h1> Firms Premised on Top to Bottom Scrutiny and Analysis</h1>
</div>
<div className="col-md-12 banner-description">
<p>Discover the top-notch Software Development firms over the globe. We investigate every possibility to give you a chance to find a portion of the eminent firms that will concur your needs and conveys superb administrations/surveillance.</p>
</div>
</div>
</div>
</div>
</section>
<section className="sf-post-listing">
<div className="container">
<div className="listing-post-main">
<div className="row">
{Companies.map((company, i) => {
return (<div className="col-md-6 col-lg-4 col-sm-12">
<div className="listing-post-card effect-image-1 zoom-effect-1">
<img src="images/listing1.jpg" className="img-fluid" />
<div className="overlay simple-overlay"><i className="fa fa-link" aria-hidden="true" /></div>
</div>
<h3>{company.title}</h3>
</div> )
})}
</div>
</div>
</div>
</section>
</div>
);
}
}
export default HomePage;
Complete component is proper just render data part cause an issue.
Error: Objects are not valid as a React child (found: object with keys
{rendered}). If you meant to render a collection of children, use an
array instead.
You need to wait for some time to API calling
Use async/await for that
async componentDidMount() {
const response = await fetch("https://jsonplaceholder.typicode.com/todos");
const data = await response.json();
this.setState({ Companies: data, loading: false });
}
https://codesandbox.io/s/bold-bash-hpefh?file=/src/App.js
I am using the Context API to manage state in a small app. I get the response OK, the Consumer has it, so I map through it and want to pass down data from it to a Product Card component through props. And the Product Card renders absolutely nothing. I get no errors whatsoever. Can anyone help me out please? Here is the code of parent component:
import Pagination from "./Pagination";
import { Consumer } from "../context";
export default class Browse extends Component {
render() {
return (
<Consumer>
{value => {
const { search } = value;
return (
<ProductsGrid>
{search.map(beer => (
<ProductCard
key={beer.id}
beerId={beer.id}
beerName={beer.name}
beerTagline={beer.tagline}
beerAbv={beer.abv}
firstBrewed={beer.first_brewed}
imageUrl={beer.image_url}
/>
))}
</ProductsGrid>
);
}}
</Consumer>
);
}
}`````
and here is the Product Card component:
```export default class ProductCard extends React.Component {
render() {
return (
<div className="product-card">
<div className="product-card-inner">
<div className="product-info-container">
<h1 className="beer-name">{this.props.beerName}</h1>
<p className="beer-type">{this.props.beerTagline}</p>
<p className="beer-alcohol">{this.props.beerAbv}%</p>
<p className="first-brewed">
First brewed: {this.props.firstBrewed}
</p>
</div>
<div className="beer-image-container">
<img src={this.props.imageUrl} alt="beer" />
</div>
<div className="price-container">
<h1>£ 3.50</h1>
</div>
<div className="button-container">
<div className="quantity-container">
<p className="minus-sign"> - </p>
<p className="qty-number"> 0 </p>
<p className="plus-sign"> + </p>
</div>
<div className="add-container">
<IoIosCart />
<p>Add</p>
</div>
</div>
</div>
</div>
);
}
}```
I am new at React. Will be glad if someone can help:
I have parent (Dashboard) which contains all data. This data is passed to the children component (OnBoardingCard).
How can I render n times the OnBoardingCard component based on the data in the object at Dashboard without using the [num](in this case 3 times - 3x OnBoarding Cards;)?
Thank you!!
Parent- Dashboard
const cardData = [
{
svg: icon1,
title: 'Add',
content: 'add more'},
{
svg: icon2,
title: 'remove',
content: 'remove'
},
{
svg: icon3,
title: 'move',
content: 'move down'
}];
class Dashboard extends Component {
render() {
return (
<Section>
<OnboardingCard listData={cardData}/>
</Section>
);
} }
Children- OnBoardingCard
import Dashboard from "../../../../screens/Dashboard/index.js";
class OnboardingCard extends Component {
render() {
return (
<div className={styles.cardHolder}>
<div className={styles.fullCard}>
<div className={styles.onboardingCard}>
<div className={styles.iconBackground}>
<img src={this.props.listData[0].svg} />
</div>
<div className={styles.title}>{this.props.listData[0].title}</div>
</div>
<p className={styles.cardDescription}>
{this.props.listData[0].content}
</p>
</div>
</div>
); }}
When you are using a map inside render assign a unique key to its child component.
render(){
return(
{this.props.listData.map((item, i) =>
<div className={styles.cardHolder} key={i}>
<div className={styles.fullCard}>
<div className={styles.onboardingCard}>
<div className={styles.iconBackground}>
<img src={this.props.listData[0].svg} />
</div>
<div className={styles.title}>{this.props.listData[0].title}</div>
</div>
<p className={styles.cardDescription}>
{this.props.listData[0].content}
</p>
</div>
</div>
)}
);
}
You can use map function,
like this,
{this.props.listData.map((item)=>
<div className={styles.cardHolder}>
<div className={styles.fullCard}>
<div className={styles.onboardingCard}>
<div className={styles.iconBackground}>
<img src={item.svg} />
</div>
<div className={styles.title}>{item.title}</div>
</div>
<p className={styles.cardDescription}>
{item.content}
</p>
</div>
</div>)}
<Section>
<div className={styles.cardRow}>
{cardData.map((card, i) => (
<OnboardingCard {...card} key={i} />
))}
</div>
</Section>
This is what I meant (and wanted to do). So this solves my question. Thanks everyone!!
Following is my code to retrieve data from firebase and view it in a bootstrap carousel. I can see the values in the console but I'm not able to get it in the props on another component.
class JobOfferSlider extends Component {
componentDidMount = () => {
var ref = fire.database().ref("Employers/Employer1");
ref.orderByKey().on("child_added", (snapshot) => {
this.setState({ slidercontents: snapshot.val()})
console.log(this.state.slidercontents);
console.log(this.state.slidercontents.Title)
});
var empref = fire.database().ref("Employers/");
empref.orderByKey().on("child_added", (snapshot) => {
this.setState({ employers: snapshot.key})
console.log(this.state.employers);
});
}
state ={
slidercontents : [], employers : []
}
and i use the props in the following jsx file
class Slidercontent extends Component {
componentWillUpdate = ()=>{
console.log(this.props.employers);
}
render() {
return (
<div className="col-sm text-center border rounded shadow p-3 m-3">
<div className="row">
<div className="col-md-3">
<div className="profilepic"></div>
</div>
<div className="col-md-9">
<h6 className="pt-2 float-left">{this.props.employers}</h6>
</div>
</div>
<h5 className="font-weight-bold pt-3 text-left">{this.props.slidercontents.Description}</h5>
<h5 className="font-weight-bold pt-3 text-left ">{this.props.slidercontents.RatePerHour}</h5>
<div className="row pt-3">
<div className="col-md-2">
<div><i class="fas fa-map-marker-alt"></i></div>
</div>
<div className="col-md-5">
<p className="float-left">{this.props.slidercontents}</p>
</div>
<div className="col-md-5">
<p className="float-right">5 mins ago</p>
</div>
</div>
</div>
);
}
}
But the props stays undefined.... any help on how to access the state values?
Pass the parent component's state as props to the child component (in the render function):
render() {
return <Slidercontent employers={this.state.employers}
}
This way, you can access the employers in the child component by:
{this.props.employers}
I'm stuck with this error that I'm getting in babel:
UnCaught TypeError: Cannot read property 'term' of null This is happening as I'm passing the state of the component into the playlists prop of the Playlist child component.
class PlaylistSearchBar extends React.Component{
constuctor(){
super();
const initialState = {
term: {tracks: [], playlists: []}
}
this.state = {
...initialState
};
}
return(
<div>
<div className="main">
<div className="ui massive icon input">
<input type="text" placeholder="Search for a song or artist..." className="js-search input-search"/>
<i className="search icon js-submit"></i>
</div>
<button onclick={localStorageClear()} className="clear">Clear Playlist</button>
</div>
<div className="search-results js-search-results ui cards">
</div>
Error here at term --> <Playlist playlists = {this.state.term.playlists} setTracksToNil = {this.setState({tracks: []})} embedItems = {this.getEmbed}/>
</div>
);
Any help would be appreciated. Thanks.
A couple of errors, constructor was misspelled, and you didn't include a render function.
class PlaylistSearchBar extends React.Component {
constructor(props) {
super(props);
const initialState = {
term: { tracks: [], playlists: [] }
}
this.state = {
...initialState
};
}
render() {
return (
<div>
<div className="main">
<div className="ui massive icon input">
<input type="text" placeholder="Search for a song or artist..." className="js-search input-search" />
<i className="search icon js-submit"></i>
</div>
<button onclick={localStorageClear()} className="clear">Clear Playlist</button>
</div>
<div className="search-results js-search-results ui cards">
</div>
<Playlist playlists={this.state.term.playlists} setTracksToNil={this.setState({ tracks: [] })} embedItems={this.getEmbed} />
</div>
);
}
}