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}
Related
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?
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'm building a NetFlix clone main page.
I have already the list of movies,tv series ecc.. rendered horizontal.
I'd like to click on the next arrow and slide only the relative section.
Now if I click the next arrow on the first section, the second one above scroll and I don't want that..
How can I achieve it?
I tried to google it and some tutorials but I can't find how to target elements in the same parent with onClick.
Thank you very much
class App extends React.Component {
state = { moviesNow: [], tvSeries: [], actionMovies: [], animation: [] };
containerSection = React.createRef();
handleClick = e => {
this.containerSection.current.style.transform = `translateX(-100%)`;
};
render() {
return (
<div className="container">
<h1 className="section-title">Now playing</h1>
<div className="wrapper">
<div className="nextArrow" onClick={this.handleClick}>
<img src={nextArrow} alt="" />
</div>
<div ref={this.containerSection} className="container-section">
<MovieItem movies={this.state.moviesNow} />
</div>
</div>
<h1 className="section-title">TV Series</h1>
<div className="wrapper">
<div className="nextArrow" onClick={this.handleClick}>
<img src={nextArrow} alt="" />
</div>
<div ref={this.containerSection} className="container-section">
<MovieItem movies={this.state.tvSeries} />
</div>
</div>
You are using only one ref for two different elements, I guess that is where you issue is coming from. So I updated handleClick to be able to receive a ref as an argument and return a function that will receive the event :
handleClick = ref => e => {
ref.current.style.transform = `translateX(-100%)`;
};
Then you can use handleClick this way:
<div className="nextArrow" onClick={this.handleClick(secondContainerSection)}>
<img src={nextArrow} alt="" />
</div>
Eventually it gives you something like this:
class App extends React.Component {
state = { moviesNow: [], tvSeries: [], actionMovies: [], animation: [] };
containerSection = React.createRef();
//a new ref
secondContainerSection = React.createRef();
handleClick = ref => e => {
ref.current.style.transform = `translateX(-100%)`;
};
render() {
return (
<div className="container">
<h1 className="section-title">Now playing</h1>
<div className="wrapper">
<div className="nextArrow" onClick={this.handleClick(containerSection)}>
<img src={nextArrow} alt="" />
</div>
<div ref={this.containerSection} className="container-section">
<MovieItem movies={this.state.moviesNow} />
</div>
</div>
<h1 className="section-title">TV Series</h1>
<div className="wrapper">
<div className="nextArrow" onClick={this.handleClick(secondContainerSection)}>
<img src={nextArrow} alt="" />
</div>
<div ref={this.secondContainerSection} className="container-section">
<MovieItem movies={this.state.tvSeries} />
</div>
</div>
make a seperate component for drawer and define the ref inside it
drawer Component
class Drawer extends React.Component {
containerSection =new React.createRef();
handleClick = e => {
this.containerSection.current.style.transform = `translateX(-100%)`;
};
render() {
return (
<div className="wrapper">
<div className="nextArrow" onClick={this.handleClick}>
<img src={nextArrow} alt="" />
</div>
<div ref={this.containerSection} className="container-section">
{this.props.children}
</div>
</div>
Main component
class App extends React.Component {
state = { moviesNow: [], tvSeries: [], actionMovies: [], animation: [] };
containerSection = React.createRef();
handleClick = e => {
this.containerSection.current.style.transform = `translateX(-100%)`;
};
render() {
return (
<div className="container">
<h1 className="section-title">Now playing</h1>
<Drawer><MovieItem movies={this.state.moviesNow} /></Drawer>
<h1 className="section-title">TV Series</h1>
<Drawer><MovieItem movies={this.state.tvSeries} /></Drawer>
</div>);
I failed to call two funtion in componentDidMount.When I clicked bangla its change and when i clicke english its change but during routing it stays only english so i wanted to set the state in componentDidMount,but it only invoke one funtion.if click the bangla it set bangla but when i change the routing its remain the same lang. so how can i set it.
import React, { Component } from 'react';
import { connect } from "react-redux";
import {setLanguage} from "../../actions";
import { Link } from "react-router-dom";
class MenuComp extends Component {
constructor(props){
super(props);
this.setLang = this.setLang.bind(this);
this.state= {
"maintitle": {
"titlelist": [
{"title1":"Timetable"},
{"title2":"Ticket Prices"},
{"title3":"About Us"}
]
}
};
}
setLang(lang){
this.props.setLanguage(lang);
this.props.history.push('/menu');
}
changeLanguage = () => {
this.setState({
"maintitle": {
"titlelist": [
{"title1":"সময়সূচী"},
{"title2":"টিকেটর মূল্য"},
{"title3":"আমাদের সম্পর্কে"}
]
}
});
};
changeLang = () => {
this.setState({
"maintitle": {
"titlelist": [
{"title1":"Timetable"},
{"title2":"Ticket Prices"},
{"title3":"About Us"}
]
}
});
};
componentDidMount() {
this.changeLanguage();
this.changeLang();
}
render() {
return (
<div className="Menu">
<div className="menu-header">
<div className="container-fluid p-0">
<div className="row m-0">
<div className="col-md-4 p-0 d-flex justify-content-end">
<div className="align-self-center">
<a className="lang" onClick={() => { this.setLang('bn'); this.changeLanguage(); }}>Bangla</a> |
<a className="lang l-active" onClick={() => { this.setLang('en'); this.changeLang(); }}>English</a>
</div>
</div>
</div>
</div>
</div>
<main className="navigation">
<div className="container-fluid p-0">
<div className="row m-0">
<div className="col-md-4 pl-0">
<Link to="/timetable" className="lang">
<div className="card-content">
<h6 className="card-title">{
this.state.maintitle.titlelist.map((title, i)=>{
return (<p key={i}>{title.title1} </p>)
})
}</h6>
</div>
</Link>
</div>
<div className="col-md-4 pl-0">
<Link to="/ticketprice" className="lang">
<div className="card-content">
<h6 className="card-title">{
this.state.maintitle.titlelist.map((title, i)=>{
return (<p key={i}>{title.title2} </p>)
})
}</h6>
</div>
</Link>
</div>
</Link>
</div>
</div>
</div>
</main>
</div>
);
}
}
function mapStateToProps(state){
return {
lang: state.lang.lang
}
}
const Menu = connect(mapStateToProps, {setLanguage})(withRouter(MenuComp));
export default Menu;
It's an asynchronous problem. So, the setState method runs asynchronously. This makes reading this.state right after calling setState() a potential pitfall.
So, the lines inside your componentDidMount method get executed, however, you can't predict which one of them will finish before the other.
Now, I don't completely understand what you're trying to achieve, but instead, use componentDidUpdate or a setState callback (setState(updater, callback)): something like this:
this.setState((state, props)=> ({
"maintitle": {
"titlelist": [
{"title1":"সময়সূচী"},
{"title2":"টিকেটর মূল্য"},
{"title3":"আমাদের সম্পর্কে"}
]
}
}), ()=> {// do what you want next!})
// (this could be inside your componentDidMount!
If that didn't help, please let me know!