REACT : empty render despite no errors - reactjs

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>
);
}
}```

Related

How to add different events with this Class |REACT JS|

I wrote down the code below.
My outcome should be 4 buttons that increment and decrement a value.
Is working but all buttons change at the same time!
The outcome I would like to get button by button and not at the same time.
I've already tried with an Array but seems I'm not on the right way!
import React from 'react';
class Counter extends React.Component {
constructor() {
super();
this.state = {
cnt: 0
};
}
handleDecrement = () => {
this.setState({
cnt: this.state.cnt + 1
});
}
handleIncrement = () => {
this.setState({
cnt: this.state.cnt - 1
});
}
render() {
return (
<><div className = "btn"></div>
<header>
<h1>Tarantino Shop</h1>
</header>
<div>
<img src= "images/walltara.png" alt="cart" width = "80%"/>
</div>
<div className="divprimario">
<div className="items">
<img src= "images/tara1.jpg" alt="cart" />
<div className = "titles"> T-Shirt Pulp Fiction</div>
<div>
<button onClick={this.handleDecrement}>+</button>
<p>{this.state.cnt} </p>
<button onClick={this.handleIncrement}>-</button>
</div>
</div>
<div className="items">
<img src= "images/tara2.jpg" alt="cart" />
<div className = "titles">T-Shirt Tarantino </div>
<div>
<button onClick={this.handleDecrement}>+</button>
<p>{this.state.cnt} </p>
<button onClick={this.handleIncrement}>-</button>
</div>
</div>
<div className="items">
<img src= "images/tara3.jpg" alt="cart" />
<div className = "titles">T-Shirt Le Iene</div>
<div>
<button onClick={this.handleDecrement}>+</button>
<p>{this.state.cnt} </p>
<button onClick={this.handleIncrement}>-</button>
</div>
</div>
<div className="items">
<img src= "images/tara4.jpg" alt="cart" />
<div className = "titles">T-Shirt Random</div>
<div>
<button onClick={this.handleDecrement}>+</button>
<p>{this.state.cnt} </p>
<button onClick={this.handleIncrement}>-</button>
</div>
</div>
</div>
</>
);
}
}
export default Counter;
So, why all the buttons change at the same time? What am I'm doing wrong?
you are only using one variable cnt to keep track of the count. If you want them to update separately, each button must increment or decrement a different state variable.
For example you could use pulpFictionCnt, tarantinoCnt etc to keep track of the different counts.
Keep a separate component for your Counter and provide other data as props.
import React from "react";
class Counter extends React.Component {
constructor() {
super();
this.state = {
cnt: 0
};
}
handleDecrement = () => {
this.setState({
cnt: this.state.cnt + 1
});
};
handleIncrement = () => {
this.setState({
cnt: this.state.cnt - 1
});
};
render() {
return (
<>
<div className="divprimario">
<div className="items">
<img src="images/tara1.jpg" alt="cart" />
<div className="titles">{this.props.title}</div>
<div>
<button onClick={this.handleDecrement}>+</button>
<p>{this.state.cnt} </p>
<button onClick={this.handleIncrement}>-</button>
</div>
</div>
</div>
</>
);
}
}
export default Counter;
Following may be some other component,
import { StrictMode } from "react";
import ReactDOM from "react-dom";
import Counter from "./Counter";
const rootElement = document.getElementById("root");
ReactDOM.render(
<StrictMode>
<div>
<div className="btn"></div>
<header>
<h1>Tarantino Shop</h1>
</header>
<div>
<img src="images/walltara.png" alt="cart" width="80%" />
</div>
<Counter title={"T-Shirt Pulp Fiction"} />
<Counter title={"T-Shirt Tarantino"} />
<Counter title={"T-Shirt Le Iene"} />
<Counter title={"T-Shirt Random"} />
</div>
</StrictMode>,
rootElement
);
Sandbox code here => https://codesandbox.io/s/laughing-bhabha-zsyvw?file=/src/Counter.js

Render N times component based on the data in object

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!!

React Instant Search recover right data in function

I work actually in my first React Project for a little startup, an "search and add to your collection" app. For the search feature, i use React Instant Search by Algolia. Everything work find.
Now, for the "add to collection" feature, i know how to do that, but I can not recover the data in my function. I did a little test like this:
import React from 'react';
import withAuthorization from './withAuthorization';
import * as firebase from 'firebase';
import {database, } from '../firebase/firebase';
import Image from 'react-image-resizer';
import{InstantSearch, SearchBox, Hits, Highlight, RefinementList} from "react-instantsearch/dom";
import { orderBy } from "lodash";
function addToCollection({hit}) {
console.log('-----');
console.log('The selected item is:', hit);
console.log('------');
}
const Hit = ({hit}) =>
<div className="hit">
<div className="hit-image">
<img src={hit.avatarURL} height={150} width={150}/>
</div>
<div className="hit-content">
<div className="hit-marque">
{hit.marque}
</div>
<div className="hit-numero">
{hit.numero}
</div>
<div className="hit-marquesuite">
{hit.marquesuite}
</div>
<div className="hit-reference">
{hit.reference}
</div>
<div className="hit-cote">
{hit.cote}
</div>
<button className="btn btn-success" onClick={addToCollection}>Ajouter à ma collection</button>
</div>
</div>
const Content = () =>
<div className="content container-fluid text-center">
<div className="row">
<div className="col-lg">
<Hits hitComponent={Hit} key ={Hit}/>
</div>
</div>
</div>
class Catalogue extends React.Component {
constructor(){
super();
this.state = {
catalogue: {},
};
}
render(){
if(this.state.catalogue === null) {
return <p>Le catalogue est vide</p>
}
return (
<div class="container-fluid">
<h1 className="text-center">Catalogue de capsule</h1>
<h4 className="text-center">Rechercher une capsule</h4>
<InstantSearch
apiKey="a8de2c61b98e1ca62a5df03f1970f46a"
appId="7H3CTF406R"
indexName="catalogue">
<SearchBox translation={{placeholder:'Rechercher une capsule'}} width="500 px"/>
<Content />
</InstantSearch>
</div>
);
}
}
const authCondition = (authUser) => !!authUser;
export default withAuthorization(authCondition)(Catalogue);
So, how can I transmit the information of my const "Hit" to my function "addToCollection" when I click on button.
Thank in advance for your help
<div className="hit-content">
<div className="hit-marque"> {hit.marque} </div>
<div className="hit-numero"> {hit.numero} </div>
<div className="hit-marquesuite"> {hit.marquesuite} </div>
<div className="hit-reference"> {hit.reference} </div>
<div className="hit-cote"> {hit.cote}
</div>
How can you access hit.cote and hit.avatarurl ?

Show hide multiple elements with react

I want to use the same function showHide to show/hide each element within the parent.
When I press the button all 3 blocks reacts and hide or show.
How can I extend the function to work individualy for each div?
This is a localhost test project so I can't provide any link unfortunately.
Here you can see the final result
import React, { Component } from 'react';
class Homepage extends Component {
constructor( props ){
super( props )
this.state = {show : true};
this.showHide = this.showHide.bind(this)
}
render() {
return (
<section id="content">
<div className="top-content">
<div className="container">
<h1>React</h1>
<h2>A JavaScript library for building user interfaces</h2>
</div>
</div>
<div className="container">
<div>
<div>
<h3>Declarative</h3>
<button onClick={this.showHide} className="button-primary btn">{this.changeName()}</button>
{ this.state.show &&
<div>
<p>text</p>
<p>text</p>
</div>
}
</div>
<div>
<h3>Component-Based</h3>
<button onClick={this.showHide} className="button-primary btn">{this.changeName()}</button>
{ this.state.show &&
<div>
<p>text</p>
<p>text</p>
</div>
}
</div>
<div>
<h3>Learn Once, Write Anywhere</h3>
<button onClick={this.showHide} className="button-primary btn">{this.changeName()}</button>
{ this.state.show &&
<div>
<p>text</p>
<p>text</p>
</div>
}
</div>
</div>
</div>
</section>
);
}
changeName(){
let text = "text "
text += this.state.show === true ? "hide" : "show";
return text;
}
showHide(){
const { show } = this.state;
this.setState( { show : !show})
}
}
export default Homepage;
The problem here is that your using the same state variable for each div (this.state.show).
If you want to have the divs behave differently, they each need their own state.
import React, { Component } from 'react';
class Homepage extends Component {
constructor( props ){
super( props )
this.state = {show: [true, true,true]};
}
render() {
return (
<section id="content">
<div className="top-content">
<div className="container">
<h1>React</h1>
<h2>A JavaScript library for building user interfaces</h2>
</div>
</div>
<div className="container">
<div>
<div>
<h3>Declarative</h3>
<button onClick={()->this.showHide(0)} className="button-primary btn">{this.changeName()}</button>
{ this.state.show[0] &&
<div>
<p>text</p>
<p>text</p>
</div>
}
</div>
<div>
<h3>Component-Based</h3>
<button onClick={()->this.showHide(1)} className="button-primary btn">{this.changeName()}</button>
{ this.state.show[1] &&
<div>
<p>text</p>
<p>text</p>
</div>
}
</div>
<div>
<h3>Learn Once, Write Anywhere</h3>
<button onClick={()->this.showHide(2)} className="button-primary btn">{this.changeName()}</button>
{ this.state.show[2] &&
<div>
<p>text</p>
<p>text</p>
</div>
}
</div>
</div>
</div>
</section>
);
}
changeName(){
let text = "text "
text += this.state.show === true ? "hide" : "show";
return text;
}
showHide(num){
this.setState((prevState) => {
const newItems = [...prevState.show];
newItems[num] = !newItems[num];
return {show: newItems};
});
}
}
export default Homepage;
Obviously there are nicer ways of doing this, but this is just an example to show the separation of states.
Can't test it right now, but shouldn't be far off.
UPDATE: #Lasitha ty for the much nicer edit!

ReactJS product id is not defined

I have the problem when I use the Reactjs, I'm really new to Reactjs, so maybe it's a easy problem:
class Product extends Component{
handleUpVote() {
this.props.onVote(this.props.id)
}
render(){
return(
<div className='item'>
<div className='middle aligned content'>
<div className='header'>
<a onClick={this.handleUpVote}>
<i className='large caret up icon'></i>
</a>
{this.props.votes}
</div>
</div>
</div>
)
}
}
class ProductList extends Component {
handleProductUpVote(prductId){
console.log(productId +' was upvoted')
}
render() {
const products1 = Data.sort((a,b) => (
b.votes-a.votes
));
const products=products1.map((product) =>{
return (
<div className='ui items'>
<Product
key={'product-'+product.id}
id={product.id}
onVote={this.handleProductUpVote}
/>
</div>
)})
return (
<div className='ui items'>
{products}
</div>
)
}}
export default ProductList;
At this line I am getting the error and i cant understand why:
this.props.onVote(this.props.id)
Forget binding this.
You need to pass the ID as a parameter to your click handler function.
Something like this:
class Product extends Component{
handleUpVote(id) {
this.props.onVote(id)
}
...
<Product
key={'product-'+product.id}
id={product.id}
onVote={() => this.handleProductUpVote(product.id)}
/>
}

Resources